dynamsoft-barcode-reader-bundle 11.0.3000 → 11.0.6000

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,8 +4,8 @@
4
4
  * @website http://www.dynamsoft.com
5
5
  * @copyright Copyright 2025, Dynamsoft Corporation
6
6
  * @author Dynamsoft
7
- * @version 11.0.3000
7
+ * @version 11.0.6000
8
8
  * @fileoverview Dynamsoft JavaScript Library for Barcode Reader
9
9
  * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/
10
10
  */
11
- !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";function e(t,e,i,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function i(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 n(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const r="undefined"==typeof self,s="function"==typeof importScripts,o=(()=>{if(!s){if(!r&&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"./"}})(),a=t=>{if(null==t&&(t="./"),r||s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var h,l,c;t.EnumScanMode=void 0,(h=t.EnumScanMode||(t.EnumScanMode={}))[h.SM_SINGLE=0]="SM_SINGLE",h[h.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE",t.EnumOptimizationMode=void 0,(l=t.EnumOptimizationMode||(t.EnumOptimizationMode={}))[l.OM_NONE=0]="OM_NONE",l[l.OM_SPEED=1]="OM_SPEED",l[l.OM_COVERAGE=2]="OM_COVERAGE",l[l.OM_BALANCE=3]="OM_BALANCE",l[l.OM_DPM=4]="OM_DPM",l[l.OM_DENSE=5]="OM_DENSE",t.EnumResultStatus=void 0,(c=t.EnumResultStatus||(t.EnumResultStatus={}))[c.RS_SUCCESS=0]="RS_SUCCESS",c[c.RS_CANCELLED=1]="RS_CANCELLED",c[c.RS_FAILED=2]="RS_FAILED";const u=t=>t&&"object"==typeof t&&"function"==typeof t.then,d=(async()=>{})().constructor;let f=class extends d{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,u(t)?e=t:"function"==typeof t&&(e=new d(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&&(u(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function g(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 m(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var p,_,v;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(p||(p={})),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"}(_||(_={})),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"}(v||(v={}));const y="undefined"==typeof self,w="function"==typeof importScripts,C=(()=>{if(!w){if(!y&&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"./"}})(),E=t=>{if(null==t&&(t="./"),y||w);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},S=t=>Object.prototype.toString.call(t),b=t=>Array.isArray?Array.isArray(t):"[object Array]"===S(t),T=t=>"number"==typeof t&&!Number.isNaN(t),I=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),x=t=>!(!I(t)||!T(t.width)||t.width<=0||!T(t.height)||t.height<=0||!T(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!A(t.tag)),O=t=>!!x(t)&&t.bytes instanceof Uint8Array,R=t=>!(!I(t)||!T(t.left)||t.left<0||!T(t.top)||t.top<0||!T(t.right)||t.right<0||!T(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),A=t=>null===t||!!I(t)&&!!T(t.imageId)&&"type"in t,D=t=>!(!I(t)||!L(t.startPoint)||!L(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),L=t=>!!I(t)&&!!T(t.x)&&!!T(t.y),M=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),F=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!L(t)),P=t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.width)||t.width<0||!T(t.height)||t.height<0),k=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))}}),N=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t<i.length&&t<n.length;++t){let e=i[t],r=n[t];if(e===r)continue;let s=parseInt(i[t]),o=parseInt(n[t]);return s===o||Number.isNaN(s)&&Number.isNaN(o)?e<r?-1:1:s<o||Number.isNaN(s)&&Number.isInteger(o)?-1:1}return i.length===n.length?0:i.length<n.length?-1:1},B=t=>{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${G[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${G[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=E(s)}return e},j=t=>{O(t)&&(t=V(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},U=async(t,e)=>{O(e)&&(e=V(e));const i=j(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},V=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===v.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;++n)e[4*n]=i[3*n],e[4*n+1]=i[3*n+1],e[4*n+2]=i[3*n+2],e[4*n+3]=255}else if(Number(t.format)===v.IPF_RGB_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;++n)e[4*n]=i[3*n+2],e[4*n+1]=i[3*n+1],e[4*n+2]=i[3*n],e[4*n+3]=255}else if(Number(t.format)===v.IPF_GRAYSCALED){const t=i.length;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;n++)e[4*n]=e[4*n+1]=e[4*n+2]=i[n],e[4*n+3]=255}else if(Number(t.format)===v.IPF_BINARY_8){const n=i.length,r=t.width,s=t.height,o=t.stride;e=new Uint8ClampedArray(r*s*4);for(let t=0;t<n;t++){let n=i[t],s=t%o,a=Math.floor(t/o);for(let t=0;t<8;t++){let i=s+t,o=4*(a*r+i);if(i>=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===v.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n<t;++n)e[4*n]=i[4*n],e[4*n+1]=i[4*n+1],e[4*n+2]=i[4*n+2],e[4*n+3]=i[4*n+3]}else if(Number(t.format)===v.IPF_ARGB_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n<t;++n)e[4*n]=i[4*n+2],e[4*n+1]=i[4*n+1],e[4*n+2]=i[4*n],e[4*n+3]=i[4*n+3]}else if(Number(t.format)===v.IPF_BINARY_8_INVERTED){const n=i.length,r=t.width,s=t.height,o=t.stride;e=new Uint8ClampedArray(r*s*4);for(let t=0;t<n;t++){let n=i[t],s=t%o,a=Math.floor(t/o);for(let t=0;t<8;t++){let i=s+t,o=4*(a*r+i);if(i>=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},G={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",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var W,Y,H,X,z,q,K,Z;let J,$,Q,tt,et,it=class t{get _isFetchingStarted(){return g(this,z,"f")}constructor(){W.add(this),Y.set(this,[]),H.set(this,1),X.set(this,p.BOPM_BLOCK),z.set(this,!1),q.set(this,void 0),K.set(this,_.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!O(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(g(this,Y,"f").length>=g(this,H,"f"))switch(g(this,X,"f")){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:if(g(this,Y,"f").push(t),I(g(this,q,"f"))&&T(g(this,q,"f").imageId)&&1==g(this,q,"f").keepInBuffer)for(;g(this,Y,"f").length>g(this,H,"f");){const t=g(this,Y,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==g(this,q,"f").imageId});g(this,Y,"f").splice(t,1)}else g(this,Y,"f").splice(0,g(this,Y,"f").length-g(this,H,"f"))}else g(this,Y,"f").push(t)}getImage(){if(0===g(this,Y,"f").length)return null;let e;if(g(this,q,"f")&&T(g(this,q,"f").imageId)){const t=g(this,W,"m",Z).call(this,g(this,q,"f").imageId);if(t<0)throw new Error(`Image with id ${g(this,q,"f").imageId} doesn't exist.`);e=g(this,Y,"f").slice(t,t+1)[0]}else e=g(this,Y,"f").pop();if([v.IPF_RGB_565,v.IPF_RGB_555,v.IPF_RGB_888,v.IPF_ARGB_8888,v.IPF_RGB_161616,v.IPF_ARGB_16161616,v.IPF_ABGR_8888,v.IPF_ABGR_16161616,v.IPF_BGR_888].includes(e.format)){if(g(this,K,"f")===_.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;t<i.length;t++)switch(e.format){case v.IPF_RGB_565:case v.IPF_RGB_555:case v.IPF_RGB_888:case v.IPF_RGB_161616:i[t]=e.bytes[3*t+2];break;case v.IPF_ARGB_8888:case v.IPF_ARGB_16161616:i[t]=e.bytes[4*t+2];break;case v.IPF_BGR_888:i[t]=e.bytes[3*t];break;case v.IPF_ABGR_8888:case v.IPF_ABGR_16161616:i[t]=e.bytes[4*t]}e.bytes=i,e.stride=e.width,e.format=v.IPF_GRAYSCALED}else if(g(this,K,"f")===_.CCUT_RGB_G_CHANNEL_ONLY){t._onLog&&t._onLog("only get G channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case v.IPF_RGB_565:case v.IPF_RGB_555:case v.IPF_RGB_888:case v.IPF_RGB_161616:case v.IPF_BGR_888:i[t]=e.bytes[3*t+1];break;case v.IPF_ARGB_8888:case v.IPF_ARGB_16161616:case v.IPF_ABGR_8888:case v.IPF_ABGR_16161616:i[t]=e.bytes[4*t+1]}e.bytes=i,e.stride=e.width,e.format=v.IPF_GRAYSCALED}else if(g(this,K,"f")===_.CCUT_RGB_B_CHANNEL_ONLY){t._onLog&&t._onLog("only get B channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case v.IPF_RGB_565:case v.IPF_RGB_555:case v.IPF_RGB_888:case v.IPF_RGB_161616:i[t]=e.bytes[3*t];break;case v.IPF_ARGB_8888:case v.IPF_ARGB_16161616:i[t]=e.bytes[4*t];break;case v.IPF_BGR_888:i[t]=e.bytes[3*t+2];break;case v.IPF_ABGR_8888:case v.IPF_ABGR_16161616:i[t]=e.bytes[4*t+2]}e.bytes=i,e.stride=e.width,e.format=v.IPF_GRAYSCALED}}else[v.IPF_NV21,v.IPF_NV12].includes(e.format)&&t._onLog&&t._onLog("NV21 or NV12 is not supported.");return e}setNextImageToReturn(t,e){if(!((...t)=>0!==t.length&&t.every(t=>T(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==S(e))throw new TypeError("Invalid 'keepInBuffer'.");m(this,q,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){m(this,q,null,"f")}hasImage(t){return g(this,W,"m",Z).call(this,t)>=0}startFetching(){m(this,z,!0,"f")}stopFetching(){m(this,z,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(m(this,H,t,"f");g(this,Y,"f")&&g(this,Y,"f").length>t;)g(this,Y,"f").shift()}getMaxImageCount(){return g(this,H,"f")}getImageCount(){return g(this,Y,"f").length}clearBuffer(){g(this,Y,"f").length=0}isBufferEmpty(){return 0===g(this,Y,"f").length}setBufferOverflowProtectionMode(t){m(this,X,t,"f")}getBufferOverflowProtectionMode(){return g(this,X,"f")}setColourChannelUsageType(t){m(this,K,t,"f")}getColourChannelUsageType(){return g(this,K,"f")}};Y=new WeakMap,H=new WeakMap,X=new WeakMap,z=new WeakMap,q=new WeakMap,K=new WeakMap,W=new WeakSet,Z=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return g(this,Y,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(J=navigator,$=J.userAgent,Q=J.platform,tt=J.mediaDevices),function(){if(!y){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:J.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:Q,search:"Win"},Mac:{str:Q},Linux:{str:Q}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||$,o=r.search||e,a=r.verStr||$,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||$,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=$.indexOf("Windows NT")&&(r="HarmonyOS"),et={browser:i,version:n,OS:r}}y&&(et={browser:"ssr",version:0,OS:"ssr"})}();const nt="undefined"!=typeof WebAssembly&&$&&!(/Safari/.test($)&&!/Chrome/.test($)&&/\(.+\s11_2_([2-6]).*\)/.test($)),rt=!("undefined"==typeof Worker),st=!(!tt||!tt.getUserMedia),ot=async()=>{let t=!1;if(st)try{(await tt.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var at,ht,lt,ct,ut,dt,ft,gt,mt;"Chrome"===et.browser&&et.version>66||"Safari"===et.browser&&et.version>13||"OPR"===et.browser&&et.version>43||"Edge"===et.browser&&et.version,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_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(at||(at={})),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"}(ht||(ht={})),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_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",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_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",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_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",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_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"}(lt||(lt={})),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",t[t.GEM_END=-1]="GEM_END"}(ct||(ct={})),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",t[t.GTM_END=-1]="GTM_END"}(ut||(ut={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(dt||(dt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(ft||(ft={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(gt||(gt={})),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"}(mt||(mt={}));const pt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_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_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_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var _t,vt,yt,wt,Ct,Et;!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_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(_t||(_t={})),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_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(vt||(vt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(yt||(yt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(wt||(wt={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(Ct||(Ct={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(Et||(Et={}));const St={},bt=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(St[t]=St[t]||new f);await Promise.all(i)},Tt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=St[t]=St[t]||new f(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let It,xt=0;const Ot=()=>xt++,Rt={};let At;const Dt=t=>{At=t,It&&It.postMessage({type:"setBLog",body:{value:!!t}})};let Lt=!1;const Mt=t=>{Lt=t,It&&It.postMessage({type:"setBDebug",body:{value:!!t}})},Ft={},Pt={},kt={dip:{wasm:!0}},Nt={std:{version:"2.0.0",path:E(C+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.0.30-dev-20250708170653",path:C,isInternal:!0}};class Bt{static get engineResourcePaths(){return Nt}static set engineResourcePaths(t){Object.assign(Nt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return At}static set _onLog(t){Dt(t)}static get _bDebug(){return Lt}static set _bDebug(t){Mt(t)}static get _workerName(){return`${Bt._bundleEnv.toLowerCase()}.bundle.worker.js`}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!St[t]&&St[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=St.core;e=!i||i.isEmpty,e||await bt("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),Ct.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||Ct.MN_DYNAMSOFT_CORE==t)return;let e=kt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=St[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await Tt(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await bt(o);const i=B(Nt),r={};for(let e of t)r[e]=kt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:Bt._bundleEnv,_useSimd:Bt._useSimd,_useMLBackend:Bt._useMLBackend};let a=new f;if(e){s.needLoadCore=!0;let t=i[`${Bt._bundleEnv.toLowerCase()}Bundle`]+Bt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),It=new Worker(t),It.onerror=t=>{let e=new Error(t.message);a.reject(e)},It.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":At&&At(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)}}),s.bLog=!!At,s.bd=Lt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await bt("core");let h=xt++;Rt[h]=t=>{if(t.success)Object.assign(Ft,t.versions),"{}"!==JSON.stringify(t.versions)&&(Bt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},It.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:nt,worker:rt,getUserMedia:st,camera:await ot(),browser:et.browser,version:et.version,OS:et.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Ot();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)}},It.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.0.30-dev-20250708170653(Worker: ${Ft.core&&Ft.core.worker||"Not Loaded"}, Wasm: ${Ft.core&&Ft.core.wasm||"Not Loaded"})`}static enableLogging(){it._onLog=console.log,Bt._onLog=console.log}static disableLogging(){it._onLog=null,Bt._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Ot();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)}},It.postMessage({type:"cfd",id:n,body:{count:t}})})}}Bt._bSupportDce4Module=-1,Bt._bSupportIRTModule=-1,Bt._versions=null,Bt._bundleEnv="DCV",Bt._useMLBackend=!1,Bt._useSimd=!0,Bt.browserInfo=et;var jt=Object.freeze({__proto__:null,CoreModule:Bt,get EnumBufferOverflowProtectionMode(){return p},get EnumCapturedResultItemType(){return at},get EnumColourChannelUsageType(){return _},get EnumCornerType(){return ht},get EnumCrossVerificationStatus(){return mt},get EnumErrorCode(){return lt},get EnumGrayscaleEnhancementMode(){return ct},get EnumGrayscaleTransformationMode(){return ut},get EnumImageCaptureDistanceMode(){return wt},get EnumImageFileFormat(){return yt},get EnumImagePixelFormat(){return v},get EnumImageTagType(){return dt},EnumIntermediateResultUnitType:pt,get EnumModuleName(){return Ct},get EnumPDFReadingMode(){return ft},get EnumRasterDataSource(){return gt},get EnumRegionObjectElementType(){return _t},get EnumSectionType(){return vt},get EnumTransformMatrixType(){return Et},ImageSourceAdapter:it,_getNorImageData:V,_saveToFile:async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await U(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),_toBlob:U,_toCanvas:j,_toImage:(t,e)=>{O(e)&&(e=V(e));const i=j(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},get bDebug(){return Lt},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:N,doOrWaitAsyncDependency:Tt,getNextTaskID:Ot,handleEngineResourcePaths:B,innerVersions:Ft,isArc:t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.radius)||t.radius<0||!T(t.startAngle)||!T(t.endAngle)),isContour:t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),isDSImageData:O,isDSRect:R,isImageTag:A,isLineSegment:D,isObject:I,isOriginalDsImageData:t=>!(!x(t)||!T(t.bytes.length)&&!T(t.bytes.ptr)),isPoint:L,isPolygon:M,isQuad:F,isRect:P,isSimdSupported:async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),mapAsyncDependency:St,mapPackageRegister:Pt,mapTaskCallBack:Rt,get onLog(){return At},productNameMap:G,requestResource:k,setBDebug:Mt,setOnLog:Dt,waitAsyncDependency:bt,get worker(){return It},workerAutoResources:kt}),Ut={license:"",scanMode:t.EnumScanMode.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:Bt.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,uiPath:o,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Vt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Gt=(async()=>{})().constructor;class Wt extends Gt{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,Vt(t)?e=t:"function"==typeof t&&(e=new Gt(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&&(Vt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Yt(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 Ht(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Xt=t=>t&&"object"==typeof t&&"function"==typeof t.then,zt=(async()=>{})().constructor;let qt=class extends zt{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,Xt(t)?e=t:"function"==typeof t&&(e=new zt(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&&(Xt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};var Kt={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1,onProcessedDocumentResultReceived:!1};const Zt=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])};let Jt=class{constructor(t){this._irrRegistryState=Kt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),Zt(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();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)}},It.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),Zt(this),await new Promise((t,e)=>{let i=Ot();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)}},It.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const $t="undefined"==typeof self,Qt="function"==typeof importScripts,te=(()=>{if(!Qt){if(!$t&&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"./"}})(),ee=t=>{if(null==t&&(t="./"),$t||Qt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ie;Bt.engineResourcePaths.cvr={version:"3.0.30-dev-20250708170725",path:te,isInternal:!0},kt.cvr={js:!0,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING,Ct.MN_DYNAMSOFT_NEURAL_NETWORK]},kt.dnn={wasm:!0,deps:[Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},Pt.cvr={};const ne="2.0.0";"string"!=typeof Bt.engineResourcePaths.std&&N(Bt.engineResourcePaths.std.version,ne)<0&&(Bt.engineResourcePaths.std={version:ne,path:ee(te+`../../dynamsoft-capture-vision-std@${ne}/dist/`),isInternal:!0});const re="3.0.10";(!Bt.engineResourcePaths.dip||"string"!=typeof Bt.engineResourcePaths.dip&&N(Bt.engineResourcePaths.dip.version,re)<0)&&(Bt.engineResourcePaths.dip={version:re,path:ee(te+`../../dynamsoft-image-processing@${re}/dist/`),isInternal:!0});const se="2.0.10";(!Bt.engineResourcePaths.dnn||"string"!=typeof Bt.engineResourcePaths.dnn&&N(Bt.engineResourcePaths.dnn.version,se)<0)&&(Bt.engineResourcePaths.dnn={version:se,path:ee(te+`../../dynamsoft-capture-vision-dnn@${se}/dist/`),isInternal:!0});let oe=class{static getVersion(){return this._version}};var ae,he,le,ce,ue,de,fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,Se,be,Te,Ie,xe;function Oe(t,e){if(t&&t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Oe(t.referencedItem,e)}}function Re(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function Ae(t){if(t.errorCode&&-10077===t.errorCode)return void console.warn(t.message);let e=new Error(t.errorCode?`[${t.errorCode}] ${t.message}`:t.message);if(e.stack&&(e.stack=t.stack),t.isShouleThrow)throw e;t.rj&&t.rj(e)}oe._version=`3.0.30-dev-20250708170725(Worker: ${null===(ie=Ft.cvr)||void 0===ie?void 0:ie.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ae||(ae={}));const De={onTaskResultsReceived:()=>{},isFilter:!0};Rt[-2]=async t=>{Le.onDataLoadProgressChanged&&Le.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let Le=class t{constructor(){he.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(Bt.browserInfo.OS)?2048:4096,this.onCaptureError=null,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,this._dynamsoft=!0,le.set(this,null),ce.set(this,null),ue.set(this,null),de.set(this,null),fe.set(this,new Set),ge.set(this,new Set),me.set(this,new Set),pe.set(this,0),_e.set(this,!1),ve.set(this,!1),ye.set(this,!1),we.set(this,null),Ce.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Yt(this,ye,"f")}static async createInstance(e=!0){if(!Pt.license)throw Error("The `license` module cannot be found.");await Pt.license.dynamsoft(),await Bt.loadWasm();const i=new t,n=new qt;let r=Ot();return Rt[r]=async t=>{t.success?(i._instanceID=t.instanceID,i._currentSettings=JSON.parse(JSON.parse(t.outputSettings).data),oe._version=`3.0.30-dev-20250708170725(Worker: ${Ft.cvr.worker}, Wasm: ${t.version})`,Ht(i,ve,!0,"f"),Ht(i,de,i.getIntermediateResultManager(),"f"),Ht(i,ve,!1,"f"),n.resolve(i)):Ae({message:t.message,rj:n.reject,stack:t.stack})},It.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e}}),n}static async appendModelBuffer(t,e){return await Bt.loadWasm(),await new Promise((i,n)=>{let r=Ot();const s=B(Bt.engineResourcePaths);let o;Rt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Ae({message:e.errorString?e.errorString:"Append Model Buffer Failed.",rj:n,errorCode:e.errorCode}),i(e)}Ae({message:t.message,rj:n,stack:t.stack})},e?o=e:"DCV"===Bt._bundleEnv?o=s.dcvData+"models/":"DBR"===Bt._bundleEnv&&(o=s.dbrBundle+"models/"),It.postMessage({type:"cvr_appendModelBuffer",id:r,body:{modelName:t,path:o}})})}async _singleFrameModeCallback(t){for(let e of Yt(this,fe,"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;for(let t of Yt(this,fe,"f"))t.isDce?t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}):Yt(this,he,"m",Se).call(this,t,i)}setInput(t){if(Re(this),!t)return Yt(this,we,"f")&&(Yt(this,de,"f").removeResultReceiver(Yt(this,we,"f")),Ht(this,we,null,"f")),Yt(this,Ce,"f")&&(Yt(this,fe,"f").delete(Yt(this,Ce,"f")),Ht(this,Ce,null,"f")),void Ht(this,le,null,"f");if(Ht(this,le,t,"f"),t.isCameraEnhancer){Yt(this,de,"f")&&(Yt(this,le,"f")._intermediateResultReceiver.isDce=!0,Yt(this,de,"f").addResultReceiver(Yt(this,le,"f")._intermediateResultReceiver),Ht(this,we,Yt(this,le,"f")._intermediateResultReceiver,"f"));const t=Yt(this,le,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Yt(this,fe,"f").add(e),Ht(this,Ce,e,"f")}}}getInput(){return Yt(this,le,"f")}addImageSourceStateListener(t){if(Re(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Yt(this,ge,"f").add(t)}removeImageSourceStateListener(t){return Re(this),Yt(this,ge,"f").delete(t)}addResultReceiver(t){if(Re(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Yt(this,fe,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Re(this),Yt(this,fe,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Yt(this,fe,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new qt;let i=Ot();return Rt[i]=async t=>{t.success?e.resolve():Ae({message:t.message,rj:e.reject,stack:t.stack})},It.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Re(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Yt(this,me,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Re(this),Yt(this,me,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Yt(this,de,"f").removeResultReceiver(De),0===Yt(this,me,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[at.CRIT_BARCODE]:!1,[at.CRIT_TEXT_LINE]:!1,[at.CRIT_DETECTED_QUAD]:!1,[at.CRIT_DESKEWED_IMAGE]:!1},e={[at.CRIT_BARCODE]:!1,[at.CRIT_TEXT_LINE]:!1,[at.CRIT_DETECTED_QUAD]:!1,[at.CRIT_DESKEWED_IMAGE]:!1};return await Yt(this,he,"m",be).call(this,t),void await Yt(this,he,"m",Te).call(this,e)}for(let t of Yt(this,me,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(at.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(at.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(at.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(at.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(at.CRIT_BARCODE)&&([...Yt(this,de,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Yt(this,de,"f").addResultReceiver(De)),await Yt(this,he,"m",be).call(this,t.verificationEnabled),await Yt(this,he,"m",Te).call(this,t.duplicateFilterEnabled),await Yt(this,he,"m",Ie).call(this,t.duplicateForgetTime)}async startCapturing(e){if(Re(this),!this._isPauseScan)return;if(!Yt(this,le,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);const i=await this.containsTask(e);for(let t of Yt(this,me,"f"))await this.addResultFilter(t);const n=B(Bt.engineResourcePaths);return Yt(this,le,"f").isCameraEnhancer&&(i.includes("ddn")?Yt(this,le,"f").setPixelFormat(v.IPF_ABGR_8888):Yt(this,le,"f").setPixelFormat(v.IPF_GRAYSCALED)),void 0!==Yt(this,le,"f").singleFrameMode&&"disabled"!==Yt(this,le,"f").singleFrameMode?(this._templateName=e,void Yt(this,le,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(Yt(this,le,"f").getColourChannelUsageType()===_.CCUT_AUTO&&Yt(this,le,"f").setColourChannelUsageType(i.includes("ddn")?_.CCUT_FULL_CHANNEL:_.CCUT_Y_CHANNEL_ONLY),Yt(this,ue,"f")&&Yt(this,ue,"f").isPending?Yt(this,ue,"f"):(Ht(this,ue,new qt((t,i)=>{if(this.disposed)return;let r=Ot();Rt[r]=async n=>{Yt(this,ue,"f")&&!Yt(this,ue,"f").isFulfilled&&(n.success?(this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Yt(this,le,"f").startFetching(),this._loopReadVideo(e),t()},0)):Ae({message:n.message,rj:i,stack:n.stack}))},It.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:n}})}),"f"),await Yt(this,ue,"f")))}stopCapturing(){Re(this),Yt(this,le,"f")&&(Yt(this,le,"f").isCameraEnhancer&&void 0!==Yt(this,le,"f").singleFrameMode&&"disabled"!==Yt(this,le,"f").singleFrameMode?Yt(this,le,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Yt(this,he,"m",xe).call(this),Yt(this,le,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Ht(this,ue,null,"f"),Yt(this,le,"f").setColourChannelUsageType(_.CCUT_AUTO)))}async containsTask(t){return Re(this),await new Promise((e,i)=>{let n=Ot();Rt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));Ae({message:t.message,rj:i,stack:t.stack})},It.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Ht(this,_e,!0,"f"),Yt(this,le,"f").isBufferEmpty())if(Yt(this,le,"f").hasNextImageToFetch())for(let t of Yt(this,ge,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ae.ISS_BUFFER_EMPTY);else if(!Yt(this,le,"f").hasNextImageToFetch())for(let t of Yt(this,ge,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ae.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Yt(this,le,"f").isBufferEmpty()&&Yt(this,le,"f").isCameraEnhancer)try{Yt(this,le,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Yt(this,le,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Yt(this,le,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Yt(this,le,"f").isCameraEnhancer&&Yt(this,le,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Yt(this,le,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Yt(this,fe,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of Yt(this,fe,"f"))if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify,_isPauseScan:this._isPauseScan}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}else{for(let t of Yt(this,me,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onProcessedDocumentResultReceived(n);Yt(this,he,"m",Se).call(this,e,n)}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()-i),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,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Yt(this,le,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Yt(this,le,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async capture(e,i){let n;if(Re(this),i||(i=t._defaultTemplate),Ht(this,_e,!1,"f"),O(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await k(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(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(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,o=Math.max(r,s);o>this.maxImageSideLength?(Ht(this,pe,this.maxImageSideLength/o,"f"),i=Math.round(r*Yt(this,pe,"f")),n=Math.round(s*Yt(this,pe,"f"))):(i=r,n=s),Yt(this,ce,"f")||Ht(this,ce,document.createElement("canvas"),"f");const a=Yt(this,ce,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,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,o=Math.max(r,s);o>this.maxImageSideLength?(Ht(this,pe,this.maxImageSideLength/o,"f"),i=Math.round(r*Yt(this,pe,"f")),n=Math.round(s*Yt(this,pe,"f"))):(i=r,n=s),Yt(this,ce,"f")||Ht(this,ce,document.createElement("canvas"),"f");const a=Yt(this,ce,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Ot();const l=B(Bt.engineResourcePaths),c=new qt;return Rt[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;0!==t.errorCode&&Ae({message:t.errorString,errorCode:t.errorCode,rj:c.reject}),e.bytes=i.bytes;for(let i of t.items)0!==Yt(this,pe,"f")&&Oe(i,Yt(this,pe,"f")),i.type===at.CRIT_ORIGINAL_IMAGE?i.imageData=e:[at.CRIT_DESKEWED_IMAGE,at.CRIT_ENHANCED_IMAGE].includes(i.type)?Pt.ddn&&Pt.ddn.handleDeskewedAndEnhancedImageResultItem(i):i.type===at.CRIT_PARSED_RESULT&&Pt.dcp&&Pt.dcp.handleParsedResultItem(i);const n=t.processedDocumentResult;if(n){if(n.deskewedImageResultItems)for(let t=0;t<n.deskewedImageResultItems.length;t++)Pt.ddn&&Pt.ddn.handleDeskewedAndEnhancedImageResultItem(n.deskewedImageResultItems[t]);if(n.enhancedImageResultItems)for(let t=0;t<n.enhancedImageResultItems.length;t++)Pt.ddn&&Pt.ddn.handleDeskewedAndEnhancedImageResultItem(n.enhancedImageResultItems[t])}const r=t.parsedResult;if(r)for(let t=0;t<r.parsedResultItems.length;t++)Pt.dcp&&Pt.dcp.handleParsedResultItem(r.parsedResultItems[t]);return Yt(this,he,"m",Ee).call(this,t,e),Ht(this,pe,0,"f"),c.resolve(t)}catch(i){Ae({message:i.message,rj:c.reject,stack:i.stack})}}else Ae({message:i.message,rj:c.reject,stack:i.stack})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),It.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Yt(this,_e,"f"),engineResourcePaths:l,dynamsoft:this._dynamsoft}},[n.buffer]),c}async initSettings(e){return Re(this),e&&["string","object"].includes(typeof e)?("string"==typeof e?e.trimStart().startsWith("{")||(e=await k(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Ot();Rt[r]=async r=>{if(r.success){const s=JSON.parse(r.response);0!==s.errorCode&&Ae({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode});const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}Ae({message:r.message,rj:n,stack:r.stack})},It.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})})):console.error("Invalid template.")}async outputSettings(t,e){return Re(this),await new Promise((i,n)=>{let r=Ot();Rt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Ae({message:e.errorString,rj:n,errorCode:e.errorCode}),i(JSON.parse(e.data))}Ae({message:t.message,rj:n,stack:t.stack})},It.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,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(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return Re(this),await new Promise((t,e)=>{let i=Ot();Rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Ae({message:n.errorString,rj:e,errorCode:n.errorCode}),t(JSON.parse(n.data))}Ae({message:i.message,rj:e,stack:i.stack})},It.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return Re(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Ot();Rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&Ae({message:n.errorString,rj:i,errorCode:n.errorCode});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}Ae({message:t.message,rj:i,stack:t.stack})},It.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return Re(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Ot();Rt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&Ae({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode}),this._currentSettings=await this.outputSettings("*"),i(r)}Ae({message:t.message,rj:n,stack:t.stack})},It.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return Re(this),await new Promise((t,e)=>{let i=Ot();Rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Ae({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode}),this._currentSettings=await this.outputSettings("*"),t(n)}Ae({message:i.message,rj:e,stack:i.stack})},It.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getIntermediateResultManager(){if(Re(this),!Yt(this,ve,"f")&&0!==Bt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Yt(this,de,"f")||Ht(this,de,new Jt(this),"f"),Yt(this,de,"f")}async parseRequiredResources(t){return Re(this),await new Promise((e,i)=>{let n=Ot();Rt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));Ae({message:t.message,rj:i,stack:t.stack})},It.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){Re(this),Yt(this,ue,"f")&&this.stopCapturing(),Ht(this,le,null,"f"),Yt(this,fe,"f").clear(),Yt(this,ge,"f").clear(),Yt(this,me,"f").clear(),Yt(this,de,"f")._intermediateResultReceiverSet.clear(),Ht(this,ye,!0,"f");let t=Ot();Rt[t]=t=>{t.success||Ae({message:t.message,stack:t.stack,isShouleThrow:!0})},It.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Yt(this,le,"f"),promiseStartScan:Yt(this,ue,"f"),intermediateResultManager:Yt(this,de,"f"),resultReceiverSet:Yt(this,fe,"f"),isaStateListenerSet:Yt(this,ge,"f"),resultFilterSet:Yt(this,me,"f"),compressRate:Yt(this,pe,"f"),canvas:Yt(this,ce,"f"),isScanner:Yt(this,_e,"f"),innerUseTag:Yt(this,ve,"f"),isDestroyed:Yt(this,ye,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Ot();Rt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}Ae({message:i.message,rj:e,stack:i.stack})},It.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};le=new WeakMap,ce=new WeakMap,ue=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,he=new WeakSet,Ee=function(t,e){const i=t.intermediateResult;if(i){let t=0;for(let n of Yt(this,de,"f")._intermediateResultReceiverSet){t++;for(let r of i){if(["onTaskResultsReceived","onTargetROIResultsReceived"].includes(r.info.callbackName)){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.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);t===Yt(this,de,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}t&&t.hasOwnProperty("intermediateResult")&&delete t.intermediateResult},Se=function(t,e){e.decodedBarcodesResult&&t.onDecodedBarcodesReceived&&t.onDecodedBarcodesReceived(e.decodedBarcodesResult),e.recognizedTextLinesResult&&t.onRecognizedTextLinesReceived&&t.onRecognizedTextLinesReceived(e.recognizedTextLinesResult),e.processedDocumentResult&&t.onProcessedDocumentResultReceived&&t.onProcessedDocumentResultReceived(e.processedDocumentResult),e.parsedResult&&t.onParsedResultsReceived&&t.onParsedResultsReceived(e.parsedResult),t.onCapturedResultReceived&&t.onCapturedResultReceived(e)},be=async function(t){return Re(this),await new Promise((e,i)=>{let n=Ot();Rt[n]=async t=>{if(t.success)return e(t.result);Ae({message:t.message,rj:i,stack:t.stack})},It.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Te=async function(t){return Re(this),await new Promise((e,i)=>{let n=Ot();Rt[n]=async t=>{if(t.success)return e(t.result);Ae({message:t.message,rj:i,stack:t.stack})},It.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},Ie=async function(t){return Re(this),await new Promise((e,i)=>{let n=Ot();Rt[n]=async t=>{if(t.success)return e(t.result);Ae({message:t.message,rj:i,stack:t.stack})},It.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},xe=async function(){let t=Ot();const e=new qt;return Rt[t]=async t=>{if(t.success)return e.resolve();Ae({message:t.message,rj:e.reject,stack:t.stack})},It.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},Le._defaultTemplate="Default";let Me=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}};var Fe;!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="ReadSingleBarcode",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"}(Fe||(Fe={}));var Pe=Object.freeze({__proto__:null,CaptureVisionRouter:Le,CaptureVisionRouterModule:oe,CapturedResultReceiver:Me,get EnumImageSourceState(){return ae},get EnumPresetTemplate(){return Fe},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=pt.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.onScaledColourImageUnitReceived=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 ke="undefined"==typeof self,Ne="function"==typeof importScripts,Be=(()=>{if(!Ne){if(!ke&&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"./"}})();Bt.engineResourcePaths.dce={version:"4.2.12-dev-20250709132053",path:Be,isInternal:!0},kt.dce={wasm:!1,js:!1},Pt.dce={};let je,Ue,Ve,Ge,We;function Ye(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 He(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(je=navigator,Ue=je.userAgent,Ve=je.platform,Ge=je.mediaDevices),function(){if(!ke){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:je.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:Ve,search:"Win"},Mac:{str:Ve},Linux:{str:Ve}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Ue,o=r.search||e,a=r.verStr||Ue,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Ue,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Ue.indexOf("Windows NT")&&(r="HarmonyOS"),We={browser:i,version:n,OS:r}}ke&&(We={browser:"ssr",version:0,OS:"ssr"})}();const Xe="undefined"!=typeof WebAssembly&&Ue&&!(/Safari/.test(Ue)&&!/Chrome/.test(Ue)&&/\(.+\s11_2_([2-6]).*\)/.test(Ue)),ze=!("undefined"==typeof Worker),qe=!(!Ge||!Ge.getUserMedia),Ke=async()=>{let t=!1;if(qe)try{(await Ge.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===We.browser&&We.version>66||"Safari"===We.browser&&We.version>13||"OPR"===We.browser&&We.version>43||"Edge"===We.browser&&We.version;var Ze={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,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,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,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<r;n++)i[n]&&i[n].call(this,e||{});return this.__eventListeners[t]=i.filter(function(t){return!1!==t}),this},on:function(t,e){if(this.__eventListeners||(this.__eventListeners={}),1===arguments.length)for(var i in t)this.on(i,t[i]);else this.__eventListeners[t]||(this.__eventListeners[t]=[]),this.__eventListeners[t].push(e);return this},once:function(t,i){if(1===arguments.length)for(var n in t)e.call(this,n,t[n]);else e.call(this,t,i);return this},off:function(e,i){if(!this.__eventListeners)return this;if(0===arguments.length)for(e in this.__eventListeners)t.call(this,e);else if(1===arguments.length&&"object"==typeof arguments[0])for(var n in e)t.call(this,n,e[n]);else t.call(this,e,i);return this}}}(),b.Collection={_objects:[],add:function(){if(this._objects.push.apply(this._objects,arguments),this._onObjectAdded)for(var t=0,e=arguments.length;t<e;t++)this._onObjectAdded(arguments[t]);return this.renderOnAddRemove&&this.requestRenderAll(),this},insertAt:function(t,e,i){var n=this._objects;return i?n[e]=t:n.splice(e,0,t),this._onObjectAdded&&this._onObjectAdded(t),this.renderOnAddRemove&&this.requestRenderAll(),this},remove:function(){for(var t,e=this._objects,i=!1,n=0,r=arguments.length;n<r;n++)-1!==(t=e.indexOf(arguments[n]))&&(i=!0,e.splice(t,1),this._onObjectRemoved&&this._onObjectRemoved(arguments[n]));return this.renderOnAddRemove&&i&&this.requestRenderAll(),this},forEachObject:function(t,e){for(var i=this.getObjects(),n=0,r=i.length;n<r;n++)t.call(e,i[n],n,i);return this},getObjects:function(t){return void 0===t?this._objects.concat():this._objects.filter(function(e){return e.type===t})},item:function(t){return this._objects[t]},isEmpty:function(){return 0===this._objects.length},size:function(){return this._objects.length},contains:function(t,e){return this._objects.indexOf(t)>-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,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){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/h){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*a},radiansToDegrees:function(t){return t/a},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),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),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),o=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(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.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 b.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 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;i<t.length;i++)t[i]=b.util.transformPoint(t[i],e);var n=[t[0].x,t[1].x,t[2].x,t[3].x],r=b.util.array.min(n),s=b.util.array.max(n)-r,o=[t[0].y,t[1].y,t[2].y,t[3].y],a=b.util.array.min(o);return{left:r,top:a,width:s,height:b.util.array.max(o)-a}},invertTransform:function(t){var e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0]],n=b.util.transformPoint({x:t[4],y:t[5]},i,!0);return i[4]=-n.x,i[5]=-n.y,i},toFixed:function(t,e){return parseFloat(Number(t).toFixed(e))},parseUnit:function(t,e){var i=/\D{0,2}$/.exec(t),n=parseFloat(t);switch(e||(e=b.Text.DEFAULT_SVG_FONT_SIZE),i[0]){case"mm":return n*b.DPI/25.4;case"cm":return n*b.DPI/2.54;case"in":return n*b.DPI;case"pt":return n*b.DPI/72;case"pc":return n*b.DPI/72*12;case"em":return n*e;default:return n}},falseFunction:function(){return!1},getKlass:function(t,e){return t=b.util.string.camelize(t.charAt(0).toUpperCase()+t.slice(1)),b.util.resolveNamespace(e)[t]},getSvgAttributes:function(t){var e=["instantiated_by_use","style","id","class"];switch(t){case"linearGradient":e=e.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);break;case"radialGradient":e=e.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);break;case"stop":e=e.concat(["offset","stop-color","stop-opacity"])}return e},resolveNamespace:function(t){if(!t)return b;var e,i=t.split("."),r=i.length,s=n||b.window;for(e=0;e<r;++e)s=s[i[e]];return s},loadImage:function(t,e,i,n){if(t){var r=b.util.createImage(),s=function(){e&&e.call(i,r,!1),r=r.onload=r.onerror=null};r.onload=s,r.onerror=function(){b.log("Error loading "+r.src),e&&e.call(i,null,!0),r=r.onload=r.onerror=null},0!==t.indexOf("data")&&null!=n&&(r.crossOrigin=n),"data:image/svg"===t.substring(0,14)&&(r.onload=null,b.util.loadImageInDom(r,s)),r.src=t}else e&&e.call(i,t)},loadImageInDom:function(t,e){var i=b.document.createElement("div");i.style.width=i.style.height="1px",i.style.left=i.style.top="-100%",i.style.position="absolute",i.appendChild(t),b.document.querySelector("body").appendChild(i),t.onload=function(){e(),i.parentNode.removeChild(i),i=null}},enlivenObjects:function(t,e,i,n){var r=[],s=0,o=(t=t||[]).length;function a(){++s===o&&e&&e(r.filter(function(t){return t}))}o?t.forEach(function(t,e){t&&t.type?b.util.getKlass(t.type,i).fromObject(t,function(i,s){s||(r[e]=i),n&&n(t,i,s),a()}):a()}):e&&e(r)},enlivenObjectEnlivables:function(t,e,i){var n=b.Object.ENLIVEN_PROPS.filter(function(e){return!!t[e]});b.util.enlivenObjects(n.map(function(e){return t[e]}),function(t){var r={};n.forEach(function(i,n){r[i]=t[n],e&&(e[i]=t[n])}),i&&i(r)})},enlivenPatterns:function(t,e){function i(){++r===s&&e&&e(n)}var n=[],r=0,s=(t=t||[]).length;s?t.forEach(function(t,e){t&&t.source?new b.Pattern(t,function(t){n[e]=t,i()}):(n[e]=t,i())}):e&&e(n)},groupSVGElements:function(t,e,i){var n;return t&&1===t.length?t[0]:(e&&(e.width&&e.height?e.centerPoint={x:e.width/2,y:e.height/2}:(delete e.width,delete e.height)),n=new b.Group(t,e),void 0!==i&&(n.sourcePath=i),n)},populateWithProperties:function(t,e,i){if(i&&Array.isArray(i))for(var n=0,r=i.length;n<r;n++)i[n]in t&&(e[i[n]]=t[i[n]])},createCanvasElement:function(){return b.document.createElement("canvas")},copyCanvasElement:function(t){var e=b.util.createCanvasElement();return e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0),e},toDataURL:function(t,e,i){return t.toDataURL("image/"+e,i)},createImage:function(){return b.document.createElement("img")},multiplyTransformMatrices:function(t,e,i){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]]},qrDecompose:function(t){var e=s(t[1],t[0]),i=o(t[0],2)+o(t[1],2),n=r(i),h=(t[0]*t[3]-t[2]*t[1])/n,l=s(t[0]*t[2]+t[1]*t[3],i);return{angle:e/a,scaleX:n,scaleY:h,skewX:l/a,skewY:0,translateX:t[4],translateY:t[5]}},calcRotateMatrix:function(t){if(!t.angle)return b.iMatrix.concat();var e=b.util.degreesToRadians(t.angle),i=b.util.cos(e),n=b.util.sin(e);return[i,n,-n,i,0,0]},calcDimensionsMatrix:function(t){var e=void 0===t.scaleX?1:t.scaleX,i=void 0===t.scaleY?1:t.scaleY,n=[t.flipX?-e:e,0,0,t.flipY?-i:i,0,0],r=b.util.multiplyTransformMatrices,s=b.util.degreesToRadians;return t.skewX&&(n=r(n,[1,0,Math.tan(s(t.skewX)),1],!0)),t.skewY&&(n=r(n,[1,Math.tan(s(t.skewY)),0,1],!0)),n},composeMatrix:function(t){var e=[1,0,0,1,t.translateX||0,t.translateY||0],i=b.util.multiplyTransformMatrices;return t.angle&&(e=i(e,b.util.calcRotateMatrix(t))),(1!==t.scaleX||1!==t.scaleY||t.skewX||t.skewY||t.flipX||t.flipY)&&(e=i(e,b.util.calcDimensionsMatrix(t))),e},resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)},saveObjectTransform:function(t){return{scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}},isTransparent:function(t,e,i,n){n>0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r<a&&0!=(s=o.data[r]<=0);r+=4);return o=null,s},parsePreserveAspectRatioAttribute:function(t){var e,i="meet",n=t.split(" ");return n&&n.length&&("meet"!==(i=n.pop())&&"slice"!==i?(e=i,i="meet"):n.length&&(e=n.pop())),{meetOrSlice:i,alignX:"none"!==e?e.slice(1,4):"none",alignY:"none"!==e?e.slice(5,8):"none"}},clearFabricFontCache:function(t){(t=(t||"").toLowerCase())?b.charWidthsCache[t]&&delete b.charWidthsCache[t]:b.charWidthsCache={}},limitDimsByArea:function(t,e){var i=Math.sqrt(e*t),n=Math.floor(e/i);return{x:Math.floor(i),y:n}},capValue:function(t,e,i){return Math.max(t,Math.min(e,i))},findScaleToFit:function(t,e){return Math.min(e.width/t.width,e.height/t.height)},findScaleToCover:function(t,e){return Math.max(e.width/t.width,e.height/t.height)},matrixToSVG:function(t){return"matrix("+t.map(function(t){return b.util.toFixed(t,b.Object.NUM_FRACTION_DIGITS)}).join(" ")+")"},removeTransformFromObject:function(t,e){var i=b.util.invertTransform(e),n=b.util.multiplyTransformMatrices(i,t.calcOwnMatrix());b.util.applyTransformToObject(t,n)},addTransformToObject:function(t,e){b.util.applyTransformToObject(t,b.util.multiplyTransformMatrices(e,t.calcOwnMatrix()))},applyTransformToObject:function(t,e){var i=b.util.qrDecompose(e),n=new b.Point(i.translateX,i.translateY);t.flipX=!1,t.flipY=!1,t.set("scaleX",i.scaleX),t.set("scaleY",i.scaleY),t.skewX=i.skewX,t.skewY=i.skewY,t.angle=i.angle,t.setPositionByOrigin(n,"center","center")},sizeAfterTransform:function(t,e,i){var n=t/2,r=e/2,s=[{x:-n,y:-r},{x:n,y:-r},{x:-n,y:r},{x:n,y:r}],o=b.util.calcDimensionsMatrix(i),a=b.util.makeBoundingBoxFromPoints(s,o);return{x:a.width,y:a.height}},mergeClipPaths:function(t,e){var i=t,n=e;i.inverted&&!n.inverted&&(i=e,n=t),b.util.applyTransformToObject(n,b.util.multiplyTransformMatrices(b.util.invertTransform(i.calcTransformMatrix()),n.calcTransformMatrix()));var r=i.inverted&&n.inverted;return r&&(i.inverted=n.inverted=!1),new b.Group([i],{clipPath:n,inverted:r})}},function(){var t=Array.prototype.join,e={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},i={m:"l",M:"L"};function n(t,e,i,n,r,s,o,a,h,l,c){var u=b.util.cos(t),d=b.util.sin(t),f=b.util.cos(e),g=b.util.sin(e),m=i*r*f-n*s*g+o,p=n*r*f+i*s*g+a;return["C",l+h*(-i*r*d-n*s*u),c+h*(-n*r*d+i*s*u),m+h*(i*r*g+n*s*f),p+h*(n*r*g-i*s*f),m,p]}function r(t,e,i,n){var r=Math.atan2(e,t),s=Math.atan2(n,i);return s>=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.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,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,I=-E*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;k<D;k++)L[k]=n(R,P,d,u,i,s,x,O,F,f,g),f=L[k][5],g=L[k][6],R=P,P+=M;return L}(i[6]-t,i[7]-e,s,o,h,l,a),u=0,d=c.length;u<d;u++)c[u][1]+=t,c[u][2]+=e,c[u][3]+=t,c[u][4]+=e,c[u][5]+=t,c[u][6]+=e;return c}function o(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-e))}function a(t,e,i,n,r,s,o,a){return function(h){var l,c=(l=h)*l*l,u=function(t){return 3*t*t*(1-t)}(h),d=function(t){return 3*t*(1-t)*(1-t)}(h),f=function(t){return(1-t)*(1-t)*(1-t)}(h);return{x:o*c+r*u+i*d+t*f,y:a*c+s*u+n*d+e*f}}}function h(t,e,i,n,r,s,o,a){return function(h){var l=1-h,c=3*l*l*(i-t)+6*l*h*(r-i)+3*h*h*(o-r),u=3*l*l*(n-e)+6*l*h*(s-n)+3*h*h*(a-s);return Math.atan2(u,c)}}function l(t,e,i,n,r,s){return function(o){var a,h=(a=o)*a,l=function(t){return 2*t*(1-t)}(o),c=function(t){return(1-t)*(1-t)}(o);return{x:r*h+i*l+t*c,y:s*h+n*l+e*c}}}function c(t,e,i,n,r,s){return function(o){var a=1-o,h=2*a*(i-t)+2*o*(r-i),l=2*a*(n-e)+2*o*(s-n);return Math.atan2(l,h)}}function u(t,e,i){var n,r,s={x:e,y:i},a=0;for(r=1;r<=100;r+=1)n=t(r/100),a+=o(s.x,s.y,n.x,n.y),s=n;return a}function d(t){for(var e,i,n,r,s=0,d=t.length,f=0,g=0,m=0,p=0,_=[],v=0;v<d;v++){switch(n={x:f,y:g,command:(e=t[v])[0]},e[0]){case"M":n.length=0,m=f=e[1],p=g=e[2];break;case"L":n.length=o(f,g,e[1],e[2]),f=e[1],g=e[2];break;case"C":i=a(f,g,e[1],e[2],e[3],e[4],e[5],e[6]),r=h(f,g,e[1],e[2],e[3],e[4],e[5],e[6]),n.iterator=i,n.angleFinder=r,n.length=u(i,f,g),f=e[5],g=e[6];break;case"Q":i=l(f,g,e[1],e[2],e[3],e[4]),r=c(f,g,e[1],e[2],e[3],e[4]),n.iterator=i,n.angleFinder=r,n.length=u(i,f,g),f=e[3],g=e[4];break;case"Z":case"z":n.destX=m,n.destY=p,n.length=o(f,g,m,p),f=m,g=p}s+=n.length,_.push(n)}return _.push({length:s,x:f,y:g}),_}b.util.joinPath=function(t){return t.map(function(t){return t.join(" ")}).join(" ")},b.util.parsePath=function(t){var n,r,s,o,a,h=[],l=[],c=b.rePathCommand,u="[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?\\s*",d="("+u+")"+b.commaWsp,f="([01])"+b.commaWsp+"?",g=new RegExp(d+"?"+d+"?"+d+f+f+d+"?("+u+")","g");if(!t||!t.match)return h;for(var m,p=0,_=(a=t.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi)).length;p<_;p++){o=(n=a[p]).slice(1).trim(),l.length=0;var v=n.charAt(0);if(m=[v],"a"===v.toLowerCase())for(var y;y=g.exec(o);)for(var w=1;w<y.length;w++)l.push(y[w]);else for(;s=c.exec(o);)l.push(s[0]);w=0;for(var C=l.length;w<C;w++)r=parseFloat(l[w]),isNaN(r)||m.push(r);var E=e[v.toLowerCase()],S=i[v]||v;if(m.length-1>E)for(var T=1,I=m.length;T<I;T+=E)h.push([v].concat(m.slice(T,T+E))),v=S;else h.push(m)}return h},b.util.makePathSimpler=function(t){var e,i,n,r,o,a,h=0,l=0,c=t.length,u=0,d=0,f=[];for(i=0;i<c;++i){switch(n=!1,(e=t[i].slice(0))[0]){case"l":e[0]="L",e[1]+=h,e[2]+=l;case"L":h=e[1],l=e[2];break;case"h":e[1]+=h;case"H":e[0]="L",e[2]=l,h=e[1];break;case"v":e[1]+=l;case"V":e[0]="L",l=e[1],e[1]=h,e[2]=l;break;case"m":e[0]="M",e[1]+=h,e[2]+=l;case"M":h=e[1],l=e[2],u=e[1],d=e[2];break;case"c":e[0]="C",e[1]+=h,e[2]+=l,e[3]+=h,e[4]+=l,e[5]+=h,e[6]+=l;case"C":o=e[3],a=e[4],h=e[5],l=e[6];break;case"s":e[0]="S",e[1]+=h,e[2]+=l,e[3]+=h,e[4]+=l;case"S":"C"===r?(o=2*h-o,a=2*l-a):(o=h,a=l),h=e[3],l=e[4],e[0]="C",e[5]=e[3],e[6]=e[4],e[3]=e[1],e[4]=e[2],e[1]=o,e[2]=a,o=e[3],a=e[4];break;case"q":e[0]="Q",e[1]+=h,e[2]+=l,e[3]+=h,e[4]+=l;case"Q":o=e[1],a=e[2],h=e[3],l=e[4];break;case"t":e[0]="T",e[1]+=h,e[2]+=l;case"T":"Q"===r?(o=2*h-o,a=2*l-a):(o=h,a=l),e[0]="Q",h=e[1],l=e[2],e[1]=o,e[2]=a,e[3]=h,e[4]=l;break;case"a":e[0]="A",e[6]+=h,e[7]+=l;case"A":n=!0,f=f.concat(s(h,l,e)),h=e[6],l=e[7];break;case"z":case"Z":h=u,l=d}n||f.push(e),r=e[0]}return f},b.util.getSmoothPathFromPoints=function(t,e){var i,n=[],r=new b.Point(t[0].x,t[0].y),s=new b.Point(t[1].x,t[1].y),o=t.length,a=1,h=0,l=o>2;for(e=e||0,l&&(a=t[2].x<s.x?-1:t[2].x===s.x?0:1,h=t[2].y<s.y?-1:t[2].y===s.y?0:1),n.push(["M",r.x-a*e,r.y-h*e]),i=1;i<o;i++){if(!r.eq(s)){var c=r.midPointFrom(s);n.push(["Q",r.x,r.y,c.x,c.y])}r=t[i],i+1<t.length&&(s=t[i+1])}return l&&(a=r.x>t[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,R=E.length,A=R;R--;)I=(O=1-(f=E[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;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[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n<i.length-2;)e-=i[n].length,n++;var r,s=i[n],a=e/s.length,h=s.command,l=t[n];switch(h){case"M":return{x:s.x,y:s.y,angle:0};case"Z":case"z":return(r=new b.Point(s.x,s.y).lerp(new b.Point(s.destX,s.destY),a)).angle=Math.atan2(s.destY-s.y,s.destX-s.x),r;case"L":return(r=new b.Point(s.x,s.y).lerp(new b.Point(l[1],l[2]),a)).angle=Math.atan2(l[2]-s.y,l[1]-s.x),r;case"C":case"Q":return function(t,e){for(var i,n,r,s=0,a=0,h=t.iterator,l={x:t.x,y:t.y},c=.01,u=t.angleFinder;a<e&&c>1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(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<t.length-1;r+=2)n.x=t[r],n.y=t[r+1],n=b.util.transformPoint(n,e),i[r]=n.x,i[r+1]=n.y;return i})}}(),function(){var t=Array.prototype.slice;function e(t,e,i){if(t&&0!==t.length){var n=t.length-1,r=e?t[n][e]:t[n];if(e)for(;n--;)i(t[n][e],r)&&(r=t[n][e]);else for(;n--;)i(t[n],r)&&(r=t[n]);return r}}b.util.array={fill:function(t,e){for(var i=t.length;i--;)t[i]=e;return t},invoke:function(e,i){for(var n=t.call(arguments,2),r=[],s=0,o=e.length;s<o;s++)r[s]=n.length?e[s][i].apply(e[s],n):e[s][i].call(e[s]);return r},min:function(t,i){return e(t,i,function(t,e){return t<e})},max:function(t,i){return e(t,i,function(t,e){return t>=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;r<s;r++)e[r]=t({},i[r],n)}else if(i&&"object"==typeof i)for(var o in i)"canvas"===o||"group"===o?e[o]=null:i.hasOwnProperty(o)&&(e[o]=t({},i[o],n));else e=i;else for(var o in i)e[o]=i[o];return e}b.util.object={extend:t,clone:function(e,i){return t({},e,i)}},b.util.object.extend(b.util,b.Observable)}(),function(){function t(t,e){var i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)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,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n<e.length;n++)!1!==(i=t(e,n))&&r.push(i);return r}}}(),function(){var t=Array.prototype.slice,e=function(){},i=function(){for(var t in{toString:1})if("toString"===t)return!1;return!0}(),n=function(t,e,n){for(var r in e)r in t.prototype&&"function"==typeof t.prototype[r]&&(e[r]+"").indexOf("callSuper")>-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,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h<l;h++)n(a,o[h],i);return a.prototype.initialize||(a.prototype.initialize=e),a.prototype.constructor=a,a.prototype.callSuper=s,a}}(),l=!!b.document.createElement("div").attachEvent,c=["touchstart","touchmove","touchend"],b.util.addListener=function(t,e,i,n){t&&t.addEventListener(e,i,!l&&n)},b.util.removeListener=function(t,e,i,n){t&&t.removeEventListener(e,i,!l&&n)},b.util.getPointer=function(t){var e=t.target,i=b.util.getScrollLeftTop(e),n=function(t){var e=t.changedTouches;return e&&e[0]?e[0]:t}(t);return{x:n.clientX+i.left,y:n.clientY+i.top}},b.util.isTouchEvent=function(t){return c.indexOf(t.type)>-1||"touch"===t.pointerType},d="string"==typeof(u=b.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}),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 o(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 a(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=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.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,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=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(o),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)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+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-l,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,!o){if(!f(w,C,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 h()):(d(w,C,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.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(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,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(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t<Math.abs(e)?(t=e,n=i/4):n=0===e&&0===t?i/(2*Math.PI)*Math.asin(1):i/(2*Math.PI)*Math.asin(e/t),{a:t,c:e,p:i,s:n}}function e(t,e,i){return t.a*Math.pow(2,10*(e-=1))*Math.sin((e*i-t.s)*(2*Math.PI)/t.p)}function i(t,e,i,r){return i-n(r-t,0,i,r)+e}function n(t,e,i,n){return(t/=n)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e}b.util.ease={easeInQuad:function(t,e,i,n){return i*(t/=n)*t+e},easeOutQuad:function(t,e,i,n){return-i*(t/=n)*(t-2)+e},easeInOutQuad:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,n){return i*(t/=n)*t*t+e},easeOutCubic:function(t,e,i,n){return i*((t=t/n-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,n){return i*(t/=n)*t*t*t+e},easeOutQuart:function(t,e,i,n){return-i*((t=t/n-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,n){return i*(t/=n)*t*t*t*t+e},easeOutQuint:function(t,e,i,n){return i*((t=t/n-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,n){return i*Math.sin(t/n*(Math.PI/2))+e},easeInOutSine:function(t,e,i,n){return-i/2*(Math.cos(Math.PI*t/n)-1)+e},easeInExpo:function(t,e,i,n){return 0===t?e:i*Math.pow(2,10*(t/n-1))+e},easeOutExpo:function(t,e,i,n){return t===n?e+i:i*(1-Math.pow(2,-10*t/n))+e},easeInOutExpo:function(t,e,i,n){return 0===t?e:t===n?e+i:(t/=n/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,n){return-i*(Math.sqrt(1-(t/=n)*t)-1)+e},easeOutCirc:function(t,e,i,n){return i*Math.sqrt(1-(t=t/n-1)*t)+e},easeInOutCirc:function(t,e,i,n){return(t/=n/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(i,n,r,s){var o=0;return 0===i?n:1==(i/=s)?n+r:(o||(o=.3*s),-e(t(r,r,o,1.70158),i,s)+n)},easeOutElastic:function(e,i,n,r){var s=0;if(0===e)return i;if(1==(e/=r))return i+n;s||(s=.3*r);var o=t(n,n,s,1.70158);return o.a*Math.pow(2,-10*e)*Math.sin((e*r-o.s)*(2*Math.PI)/o.p)+o.c+i},easeInOutElastic:function(i,n,r,s){var o=0;if(0===i)return n;if(2==(i/=s/2))return n+r;o||(o=s*(.3*1.5));var a=t(r,r,o,1.70158);return i<1?-.5*e(a,i,s)+n:a.a*Math.pow(2,-10*(i-=1))*Math.sin((i*s-a.s)*(2*Math.PI)/a.p)*.5+a.c+n},easeInBack:function(t,e,i,n,r){return void 0===r&&(r=1.70158),i*(t/=n)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,n,r){return void 0===r&&(r=1.70158),i*((t=t/n-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,n,r){return void 0===r&&(r=1.70158),(t/=n/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:i,easeOutBounce:n,easeInOutBounce:function(t,e,r,s){return t<s/2?.5*i(2*t,0,r,s)+e:.5*n(2*t-s,0,r,s)+.5*r+e}}}(),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.parseUnit,o=e.util.multiplyTransformMatrices,a={cx:"left",x:"left",r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing"},h={stroke:"strokeOpacity",fill:"fillOpacity"},l="font-size",c="clip-path";function u(t){return t in a?a[t]:t}function d(t,i,n,r){var a,h=Array.isArray(i);if("fill"!==t&&"stroke"!==t||"none"!==i){if("strokeUniform"===t)return"non-scaling-stroke"===i;if("strokeDashArray"===t)i="none"===i?null:i.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)i=n&&n.transformMatrix?o(n.transformMatrix,e.parseTransformAttribute(i)):e.parseTransformAttribute(i);else if("visible"===t)i="none"!==i&&"hidden"!==i,n&&!1===n.visible&&(i=!1);else if("opacity"===t)i=parseFloat(i),n&&void 0!==n.opacity&&(i*=n.opacity);else if("textAnchor"===t)i="start"===i?"left":"end"===i?"right":"center";else if("charSpacing"===t)a=s(i,r)/r*1e3;else if("paintFirst"===t){var l=i.indexOf("fill"),c=i.indexOf("stroke");i="fill",(l>-1&&c>-1&&c<l||-1===l&&c>-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r<s;r++)i=e[r],n=t.getElementsByTagName(i),o=o.concat(Array.prototype.slice.call(n));return o}function m(t,e){var i,n=!0;return(i=p(t,e.pop()))&&e.length&&(n=function(t,e){for(var i,n=!0;t.parentNode&&1===t.parentNode.nodeType&&e.length;)n&&(i=e.pop()),n=p(t=t.parentNode,i);return 0===e.length}(t,e)),i&&n&&0===e.length}function p(t,e){var i,n,r=t.nodeName,s=t.getAttribute("class"),o=t.getAttribute("id");if(i=new RegExp("^"+r,"i"),e=e.replace(i,""),o&&e.length&&(i=new RegExp("#"+o+"(?![a-zA-Z\\-]+)","i"),e=e.replace(i,"")),s&&e.length)for(n=(s=s.split(" ")).length;n--;)i=new RegExp("\\."+s[n]+"(?![a-zA-Z\\-]+)","i"),e=e.replace(i,"");return 0===e.length}function _(t,e){var i;if(t.getElementById&&(i=t.getElementById(e)),i)return i;var n,r,s,o=t.getElementsByTagName("*");for(r=0,s=o.length;r<s;r++)if(e===(n=o[r]).getAttribute("id"))return n}e.svgValidTagNamesRegEx=f(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),e.svgViewBoxElementsRegEx=f(["symbol","image","marker","pattern","view","svg"]),e.svgInvalidAncestorsRegEx=f(["pattern","defs","symbol","metadata","clipPath","mask","desc"]),e.svgValidParentsRegEx=f(["symbol","g","a","svg","clipPath","defs"]),e.cssRules={},e.gradientDefs={},e.clipPaths={},e.parseTransformAttribute=function(){function t(t,i,n){t[n]=Math.tan(e.util.degreesToRadians(i[0]))}var i=e.iMatrix,n=e.reNum,r=e.commaWsp,s="(?:(?:(matrix)\\s*\\(\\s*("+n+")"+r+"("+n+")"+r+"("+n+")"+r+"("+n+")"+r+"("+n+")"+r+"("+n+")\\s*\\))|(?:(translate)\\s*\\(\\s*("+n+")(?:"+r+"("+n+"))?\\s*\\))|(?:(scale)\\s*\\(\\s*("+n+")(?:"+r+"("+n+"))?\\s*\\))|(?:(rotate)\\s*\\(\\s*("+n+")(?:"+r+"("+n+")"+r+"("+n+"))?\\s*\\))|(?:(skewX)\\s*\\(\\s*("+n+")\\s*\\))|(?:(skewY)\\s*\\(\\s*("+n+")\\s*\\)))",o=new RegExp("^\\s*(?:(?:"+s+"(?:"+r+"*"+s+")*)?)\\s*$"),a=new RegExp(s,"g");return function(n){var r=i.concat(),h=[];if(!n||n&&!o.test(n))return r;n.replace(a,function(n){var o=new RegExp(s).exec(n).filter(function(t){return!!t}),a=o[1],l=o.slice(2).map(parseFloat);switch(a){case"translate":!function(t,e){t[4]=e[0],2===e.length&&(t[5]=e[1])}(r,l);break;case"rotate":l[0]=e.util.degreesToRadians(l[0]),function(t,i){var n=e.util.cos(i[0]),r=e.util.sin(i[0]),s=0,o=0;3===i.length&&(s=i[1],o=i[2]),t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t[4]=s-(n*s-r*o),t[5]=o-(r*s+n*o)}(r,l);break;case"scale":!function(t,e){var i=e[0],n=2===e.length?e[1]:e[0];t[0]=i,t[3]=n}(r,l);break;case"skewX":t(r,l,2);break;case"skewY":t(r,l,1);break;case"matrix":r=l}h.push(r.concat()),r=i.concat()});for(var l=h[0];h.length>1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();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,o,a,h,l=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")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"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)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,u=C.height/o),"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=C.width-r*c,b=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),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&&n<i.length;){var r=i[n],s=r.getAttribute("xlink:href")||r.getAttribute("href");if(null===s)return;var o,a,h,l,c=s.slice(1),u=r.getAttribute("x")||0,d=r.getAttribute("y")||0,f=_(t,c).cloneNode(!0),m=(f.getAttribute("transform")||"")+" translate("+u+", "+d+")",p=i.length,v=e.svgNS;if(y(f),/^svg$/i.test(f.nodeName)){var w=f.ownerDocument.createElementNS(v,"g");for(a=0,l=(h=f.attributes).length;a<l;a++)o=h.item(a),w.setAttributeNS(v,o.nodeName,o.nodeValue);for(;f.firstChild;)w.appendChild(f.firstChild);f=w}for(a=0,l=(h=r.attributes).length;a<l;a++)"x"!==(o=h.item(a)).nodeName&&"y"!==o.nodeName&&"xlink:href"!==o.nodeName&&"href"!==o.nodeName&&("transform"===o.nodeName?m=o.nodeValue+" "+m:f.setAttribute(o.nodeName,o.nodeValue));f.setAttribute("transform",m),f.setAttribute("instantiated_by_use","1"),f.removeAttribute("id"),r.parentNode.replaceChild(f,r),i.length===p&&n++}}(t);var o,a,h=e.Object.__uid++,l=y(t),c=e.util.toArray(t.getElementsByTagName("*"));if(l.crossOrigin=s&&s.crossOrigin,l.svgUid=h,0===c.length&&e.isLikelyNode){var u=[];for(o=0,a=(c=t.selectNodes('//*[name(.)!="svg"]')).length;o<a;o++)u[o]=c[o];c=u}var d=c.filter(function(t){return y(t),e.svgValidTagNamesRegEx.test(t.nodeName.replace("svg:",""))&&!function(t,e){for(;t&&(t=t.parentNode);)if(t.nodeName&&e.test(t.nodeName.replace("svg:",""))&&!t.getAttribute("instantiated_by_use"))return!0;return!1}(t,e.svgInvalidAncestorsRegEx)});if(!d||d&&!d.length)i&&i([],{});else{var f={};c.filter(function(t){return"clipPath"===t.nodeName.replace("svg:","")}).forEach(function(t){var i=t.getAttribute("id");f[i]=e.util.toArray(t.getElementsByTagName("*")).filter(function(t){return e.svgValidTagNamesRegEx.test(t.nodeName.replace("svg:",""))})}),e.gradientDefs[h]=e.getGradientDefs(t),e.cssRules[h]=e.getCSSRules(t),e.clipPaths[h]=f,e.parseElements(d,function(t,n){i&&(i(t,l,n,c),delete e.gradientDefs[h],delete e.cssRules[h],delete e.clipPaths[h])},n(l),r,s)}}};var C=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+e.reNum+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+e.reNum+"))?\\s+(.*)");i(e,{parseFontDeclaration:function(t,e){var i=t.match(C);if(i){var n=i[1],r=i[3],o=i[4],a=i[5],h=i[6];n&&(e.fontStyle=n),r&&(e.fontWeight=isNaN(parseFloat(r))?r:parseFloat(r)),o&&(e.fontSize=s(o)),h&&(e.fontFamily=h),a&&(e.lineHeight="normal"===a?1:a)}},getGradientDefs:function(t){var e,i=g(t,["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"]),n=0,r={};for(n=i.length;n--;)(e=i[n]).getAttribute("xlink:href")&&w(t,e),r[e.getAttribute("id")]=e;return r},parseAttributes:function(t,n,o){if(t){var a,f,g,p={};void 0===o&&(o=t.getAttribute("svgUid")),t.parentNode&&e.svgValidParentsRegEx.test(t.parentNode.nodeName)&&(p=e.parseAttributes(t.parentNode,n,o));var _=n.reduce(function(e,i){return(a=t.getAttribute(i))&&(e[i]=a),e},{}),v=i(function(t,i){var n={};for(var r in e.cssRules[i])if(m(t,r.split(" ")))for(var s in e.cssRules[i][r])n[s]=e.cssRules[i][r][s];return n}(t,o),e.parseStyleAttribute(t));_=i(_,v),v[c]&&t.setAttribute(c,v[c]),f=g=p.fontSize||e.Text.DEFAULT_SVG_FONT_SIZE,_[l]&&(_[l]=f=s(_[l],g));var y,w,C={};for(var E in _)w=d(y=u(E),_[E],p,f),C[y]=w;C&&C.font&&e.parseFontDeclaration(C.font,C);var S=i(p,C);return e.svgValidParentsRegEx.test(t.nodeName)?S:function(t){for(var i in h)if(void 0!==t[h[i]]&&""!==t[i]){if(void 0===t[i]){if(!e.Object.prototype[i])continue;t[i]=e.Object.prototype[i]}if(0!==t[i].indexOf("url(")){var n=new e.Color(t[i]);t[i]=n.setAlpha(r(n.getAlpha()*t[h[i]],2)).toRgba()}}return t}(S)}},parseElements:function(t,i,n,r,s){new e.ElementsParser(t,i,n,r,s).parse()},parseStyleAttribute:function(t){var e={},i=t.getAttribute("style");return i?("string"==typeof i?function(t,e){var i,n;t.replace(/;\s*$/,"").split(";").forEach(function(t){var r=t.split(":");i=r[0].trim().toLowerCase(),n=r[1].trim(),e[i]=n})}(i,e):function(t,e){var i,n;for(var r in t)void 0!==t[r]&&(i=r.toLowerCase(),n=t[r],e[i]=n)}(i,e),e):e},parsePointsAttribute:function(t){if(!t)return null;var e,i,n=[];for(e=0,i=(t=(t=t.replace(/,/g," ").trim()).split(/\s+/)).length;e<i;e+=2)n.push({x:parseFloat(t[e]),y:parseFloat(t[e+1])});return n},getCSSRules:function(t){var i,n,r=t.getElementsByTagName("style"),s={};for(i=0,n=r.length;i<n;i++){var o=r[i].textContent;""!==(o=o.replace(/\/\*[\s\S]*?\*\//g,"")).trim()&&o.split("}").filter(function(t){return t.trim()}).forEach(function(t){var r=t.split("{"),o={},a=r[1].trim().split(";").filter(function(t){return t.trim()});for(i=0,n=a.length;i<n;i++){var h=a[i].split(":"),l=h[0].trim(),c=h[1].trim();o[l]=c}(t=r[0].trim()).split(",").forEach(function(t){""!==(t=t.replace(/^svg/i,"").trim())&&(s[t]?e.util.object.extend(s[t],o):s[t]=e.util.object.clone(o))})})}return s},loadSVGFromURL:function(t,i,n,r){t=t.replace(/^\n\s*/,"").trim(),new e.util.request(t,{method:"get",onComplete:function(t){var s=t.responseXML;if(!s||!s.documentElement)return i&&i(null),!1;e.parseSVGDocument(s.documentElement,function(t,e,n,r){i&&i(t,e,n,r)},n,r)}})},loadSVGFromString:function(t,i,n,r){var s=(new e.window.DOMParser).parseFromString(t.trim(),"text/xml");e.parseSVGDocument(s.documentElement,function(t,e,n,r){i(t,e,n,r)},n,r)}})}(e),b.ElementsParser=function(t,e,i,n,r,s){this.elements=t,this.callback=e,this.options=i,this.reviver=n,this.svgUid=i&&i.svgUid||0,this.parsingOptions=r,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=s},(p=b.ElementsParser.prototype).parse=function(){this.instances=new Array(this.elements.length),this.numElements=this.elements.length,this.createObjects()},p.createObjects=function(){var t=this;this.elements.forEach(function(e,i){e.setAttribute("svgUid",t.svgUid),t.createObject(e,i)})},p.findTag=function(t){return b[b.util.string.capitalize(t.tagName.replace("svg:",""))]},p.createObject=function(t,e){var i=this.findTag(t);if(i&&i.fromElement)try{i.fromElement(t,this.createCallback(e,t),this.options)}catch(t){b.log(t)}else this.checkIfDone()},p.createCallback=function(t,e){var i=this;return function(n){var r;i.resolveGradient(n,e,"fill"),i.resolveGradient(n,e,"stroke"),n instanceof b.Image&&n._originalElement&&(r=n.parsePreserveAspectRatioAttribute(e)),n._removeTransformMatrix(r),i.resolveClipPath(n,e),i.reviver&&i.reviver(e,n),i.instances[t]=n,i.checkIfDone()}},p.extractPropertyDefinition=function(t,e,i){var n=t[e],r=this.regexUrl;if(r.test(n)){r.lastIndex=0;var s=r.exec(n)[1];return r.lastIndex=0,b[i][this.svgUid][s]}},p.resolveGradient=function(t,e,i){var n=this.extractPropertyDefinition(t,i,"gradientDefs");if(n){var r=e.getAttribute(i+"-opacity"),s=b.Gradient.fromElement(n,t,r,this.options);t.set(i,s)}},p.createClipPathCallback=function(t,e){return function(t){t._removeTransformMatrix(),t.fillRule=t.clipRule,e.push(t)}},p.resolveClipPath=function(t,e){var i,n,r,s,o=this.extractPropertyDefinition(t,"clipPath","clipPaths");if(o){r=[],n=b.util.invertTransform(t.calcTransformMatrix());for(var a=o[0].parentNode,h=e;h.parentNode&&h.getAttribute("clip-path")!==t.clipPath;)h=h.parentNode;h.parentNode.appendChild(a);for(var l=0;l<o.length;l++)i=o[l],this.findTag(i).fromElement(i,this.createClipPathCallback(t,r),this.options);o=1===r.length?r[0]:new b.Group(r),s=b.util.multiplyTransformMatrices(n,o.calcTransformMatrix()),o.clipPath&&this.resolveClipPath(o,h);var c=b.util.qrDecompose(s);o.flipX=!1,o.flipY=!1,o.set("scaleX",c.scaleX),o.set("scaleY",c.scaleY),o.angle=c.angle,o.skewX=c.skewX,o.skewY=0,o.setPositionByOrigin({x:c.translateX,y:c.translateY},"center","center"),t.clipPath=o}else delete t.clipPath},p.checkIfDone=function(){0==--this.numElements&&(this.instances=this.instances.filter(function(t){return null!=t}),this.callback(this.instances,this.elements))},function(t){var e=t.fabric||(t.fabric={});function i(t,e){this.x=t,this.y=e}e.Point?e.warn("fabric.Point is already defined"):(e.Point=i,i.prototype={type:"point",constructor:i,add:function(t){return new i(this.x+t.x,this.y+t.y)},addEquals:function(t){return this.x+=t.x,this.y+=t.y,this},scalarAdd:function(t){return new i(this.x+t,this.y+t)},scalarAddEquals:function(t){return this.x+=t,this.y+=t,this},subtract:function(t){return new i(this.x-t.x,this.y-t.y)},subtractEquals:function(t){return this.x-=t.x,this.y-=t.y,this},scalarSubtract:function(t){return new i(this.x-t,this.y-t)},scalarSubtractEquals:function(t){return this.x-=t,this.y-=t,this},multiply:function(t){return new i(this.x*t,this.y*t)},multiplyEquals:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return new i(this.x/t,this.y/t)},divideEquals:function(t){return this.x/=t,this.y/=t,this},eq:function(t){return this.x===t.x&&this.y===t.y},lt:function(t){return this.x<t.x&&this.y<t.y},lte:function(t){return this.x<=t.x&&this.y<=t.y},gt:function(t){return this.x>t.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 o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a<l;a++)r=n[a],s=n[(a+1)%l],o=i.intersectLineLine(t,e,r,s),h.appendPoints(o.points);return h.points.length>0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n<s;n++){var o=t[n],a=t[(n+1)%s],h=i.intersectLinePolygon(o,a,e);r.appendPoints(h.points)}return r.points.length>0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.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,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i<n?6:0);break;case i:r=(n-t)/l+2;break;case n:r=(t-i)/l+4}r/=6}return[Math.round(360*r),Math.round(100*s),Math.round(100*o)]},getSource:function(){return this._source},setSource:function(t){this._source=t},toRgb:function(){var t=this.getSource();return"rgb("+t[0]+","+t[1]+","+t[2]+")"},toRgba:function(){var t=this.getSource();return"rgba("+t[0]+","+t[1]+","+t[2]+","+t[3]+")"},toHsl:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsl("+e[0]+","+e[1]+"%,"+e[2]+"%)"},toHsla:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsla("+e[0]+","+e[1]+"%,"+e[2]+"%,"+t[3]+")"},toHex:function(){var t,e,i,n=this.getSource();return t=1===(t=n[0].toString(16)).length?"0"+t:t,e=1===(e=n[1].toString(16)).length?"0"+e:e,i=1===(i=n[2].toString(16)).length?"0"+i:i,t.toUpperCase()+e.toUpperCase()+i.toUpperCase()},toHexa:function(){var t,e=this.getSource();return t=1===(t=(t=Math.round(255*e[3])).toString(16)).length?"0"+t:t,this.toHex()+t.toUpperCase()},getAlpha:function(){return this.getSource()[3]},setAlpha:function(t){var e=this.getSource();return e[3]=t,this.setSource(e),this},toGrayscale:function(){var t=this.getSource(),e=parseInt((.3*t[0]+.59*t[1]+.11*t[2]).toFixed(0),10),i=t[3];return this.setSource([e,e,e,i]),this},toBlackWhite:function(t){var e=this.getSource(),i=(.3*e[0]+.59*e[1]+.11*e[2]).toFixed(0),n=e[3];return t=t||127,i=Number(i)<Number(t)?0:255,this.setSource([i,i,i,n]),this},overlayWith:function(t){t instanceof i||(t=new i(t));var e,n=[],r=this.getAlpha(),s=this.getSource(),o=t.getSource();for(e=0;e<3;e++)n.push(Math.round(.5*s[e]+.5*o[e]));return n[3]=r,this.setSource(n),this}},e.Color.reRGBa=/^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/i,e.Color.reHSLa=/^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/i,e.Color.reHex=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,e.Color.colorNameMap={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#00FFFF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blue:"#0000FF",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#FF00FF",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#00FF00",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#663399",red:"#FF0000",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFFFFF",whitesmoke:"#F5F5F5",yellow:"#FFFF00",yellowgreen:"#9ACD32"},e.Color.fromRgb=function(t){return i.fromSource(i.sourceFromRgb(t))},e.Color.sourceFromRgb=function(t){var e=t.match(i.reRGBa);if(e){var n=parseInt(e[1],10)/(/%$/.test(e[1])?100:1)*(/%$/.test(e[1])?255:1),r=parseInt(e[2],10)/(/%$/.test(e[2])?100:1)*(/%$/.test(e[2])?255:1),s=parseInt(e[3],10)/(/%$/.test(e[3])?100:1)*(/%$/.test(e[3])?255:1);return[parseInt(n,10),parseInt(r,10),parseInt(s,10),e[4]?parseFloat(e[4]):1]}},e.Color.fromRgba=i.fromRgb,e.Color.fromHsl=function(t){return i.fromSource(i.sourceFromHsl(t))},e.Color.sourceFromHsl=function(t){var e=t.match(i.reHSLa);if(e){var r,s,o,a=(parseFloat(e[1])%360+360)%360/360,h=parseFloat(e[2])/(/%$/.test(e[2])?100:1),l=parseFloat(e[3])/(/%$/.test(e[3])?100:1);if(0===h)r=s=o=l;else{var c=l<=.5?l*(h+1):l+h-l*h,u=2*l-c;r=n(u,c,a+1/3),s=n(u,c,a),o=n(u,c,a-1/3)}return[Math.round(255*r),Math.round(255*s),Math.round(255*o),e[4]?parseFloat(e[4]):1]}},e.Color.fromHsla=i.fromHsl,e.Color.fromHex=function(t){return i.fromSource(i.sourceFromHex(t))},e.Color.sourceFromHex=function(t){if(t.match(i.reHex)){var e=t.slice(t.indexOf("#")+1),n=3===e.length||4===e.length,r=8===e.length||4===e.length,s=n?e.charAt(0)+e.charAt(0):e.substring(0,2),o=n?e.charAt(1)+e.charAt(1):e.substring(2,4),a=n?e.charAt(2)+e.charAt(2):e.substring(4,6),h=r?n?e.charAt(3)+e.charAt(3):e.substring(6,8):"FF";return[parseInt(s,16),parseInt(o,16),parseInt(a,16),parseFloat((parseInt(h,16)/255).toFixed(2))]}},e.Color.fromSource=function(t){var e=new i;return e.setSource(t),e})}(e),function(t){var e=t.fabric||(t.fabric={}),i=["e","se","s","sw","w","nw","n","ne","e"],n=["ns","nesw","ew","nwse"],r={},s="left",o="top",a="right",h="bottom",l="center",c={top:h,bottom:o,left:a,right:s,center:l},u=e.util.radiansToDegrees,d=Math.sign||function(t){return(t>0)-(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===l&&t.originY===l}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,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.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,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,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)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),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 o=f(n,e);return i[o]+"-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,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+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)<f?c=m:Math.abs(c-g)<f&&(c=g)}return c<0&&(c=360+c),c%=360,a=s.angle!==c,s.angle=c,a})),r.scalingEqually=w("scaling",y(function(t,e,i,n){return I(t,e,i,n)})),r.scalingX=w("scaling",y(function(t,e,i,n){return I(t,e,i,n,{by:"x"})})),r.scalingY=w("scaling",y(function(t,e,i,n){return I(t,e,i,n,{by:"y"})})),r.scalingYOrSkewingX=function(t,e,i,n){return t[e.target.canvas.altActionKey]?r.skewHandlerX(t,e,i,n):r.scalingY(t,e,i,n)},r.scalingXOrSkewingY=function(t,e,i,n){return t[e.target.canvas.altActionKey]?r.skewHandlerY(t,e,i,n):r.scalingX(t,e,i,n)},r.changeWidth=w("resizing",y(function(t,e,i,n){var r=e.target,s=C(e,e.originX,e.originY,i,n),o=r.strokeWidth/(r.strokeUniform?r.scaleX:1),a=p(e)?2:1,h=r.width,l=Math.abs(s.x*a/r.scaleX)-o;return r.set("width",Math.max(l,0)),h!==l})),r.skewHandlerX=function(t,e,i,n){var r,h=e.target,c=h.skewX,u=e.originY;return!h.lockSkewingX&&(0===c?r=C(e,l,l,i,n).x>0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),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,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},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,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/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[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),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 o,a,h,l,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);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},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,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[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 b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,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,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.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,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["<linearGradient ",o,' x1="',a.x1,'" y1="',a.y1,'" x2="',a.x2,'" y2="',a.y2,'">\n']:"radial"===this.type&&(s=["<radialGradient ",o,' cx="',l?a.x1:a.x2,'" cy="',l?a.y1:a.y2,'" r="',l?a.r1:a.r2,'" fx="',l?a.x2:a.x1,'" fy="',l?a.y2:a.y1,'">\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n<r;n++)h[n].offset=1-h[n].offset;var m=Math.min(a.r1,a.r2);if(m>0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n<r;n++)h[n].offset+=p*(1-h[n].offset)}}for(n=0,r=h.length;n<r;n++){var _=h[n];s.push("<stop ",'offset="',100*_.offset+"%",'" style="stop-color:',_.color,void 0!==_.opacity?";stop-opacity: "+_.opacity:";",'"/>\n')}return s.push("linear"===this.type?"</linearGradient>\n":"</radialGradient>\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;i<n;i++){var s=this.colorStops[i].color,o=this.colorStops[i].opacity,a=this.colorStops[i].offset;void 0!==o&&(s=new b.Color(s).setAlpha(o).toRgba()),e.addColorStop(a,s)}return e}}}),b.util.object.extend(b.Gradient,{fromElement:function(e,i,n,r){var s=parseFloat(n)/(/%$/.test(n)?100:1);s=s<0?0:s>1?1:s,isNaN(s)&&(s=1);var o,a,h,l,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?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=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)),h=c.length;h--;)f.push(t(c[h],s));return l=b.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,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,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,o="";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?o=e.src:e.toDataURL&&(o=e.toDataURL()),'<pattern id="SVGID_'+this.id+'" x="'+r+'" y="'+s+'" width="'+i+'" height="'+n+'">\n<image x="0" y="0" width="'+e.width+'" height="'+e.height+'" xlink:href="'+o+'"></image>\n</pattern>\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,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'<filter id="SVGID_'+this.id+'" y="-'+r+'%" height="'+(100+2*r)+'%" x="-'+n+'%" width="'+(100+2*n)+'%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="'+i(this.blur?this.blur/2:0,s)+'"></feGaussianBlur>\n\t<feOffset dx="'+i(o.x,s)+'" dy="'+i(o.y,s)+'" result="oBlur" ></feOffset>\n\t<feFlood flood-color="'+a.toRgb()+'" flood-opacity="'+a.getAlpha()+'"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\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,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=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=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;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,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i<n;i++)(e=this._objects[i]).group||e.setCoords(!0);return r&&r.setCoords(),s&&s.setCoords(!0),o&&o.setCoords(!0),this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll(),this},zoomToPoint:function(t,e){var i=t,n=this.viewportTransform.slice(0);t=r(t,s(this.viewportTransform)),n[0]=e,n[3]=e;var o=r(t,n);return n[4]+=i.x-o.x,n[5]+=i.y-o.y,this.setViewportTransform(n)},setZoom:function(t){return this.zoomToPoint(new b.Point(0,0),t),this},absolutePan:function(t){var e=this.viewportTransform.slice(0);return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)},relativePan:function(t){return this.absolutePan(new b.Point(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))},getElement:function(){return this.lowerCanvasEl},_onObjectAdded:function(t){this.stateful&&t.setupState(),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added")},_onObjectRemoved:function(t){this.fire("object:removed",{target:t}),t.fire("removed"),delete t.canvas},clearContext:function(t){return t.clearRect(0,0,this.width,this.height),this},getContext:function(){return this.contextContainer},clear:function(){return this.remove.apply(this,this.getObjects()),this.backgroundImage=null,this.overlayImage=null,this.backgroundColor="",this.overlayColor="",this._hasITextHandlers&&(this.off("mouse:up",this._mouseUpITextHandler),this._iTextInstances=null,this._hasITextHandlers=!1),this.clearContext(this.contextContainer),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll(),this},renderAll:function(){var t=this.contextContainer;return this.renderCanvas(t,this._objects),this},renderAndReset:function(){this.isRendering=0,this.renderAll()},requestRenderAll:function(){return this.isRendering||(this.isRendering=b.util.requestAnimFrame(this.renderAndResetBound)),this},calcViewportBoundaries:function(){var t={},e=this.width,i=this.height,n=s(this.viewportTransform);return t.tl=r({x:0,y:0},n),t.br=r({x:e,y:i},n),t.tr=new b.Point(t.br.x,t.tl.y),t.bl=new b.Point(t.tl.x,t.br.y),this.vptCoords=t,t},cancelRequestedRender:function(){this.isRendering&&(b.util.cancelAnimFrame(this.isRendering),this.isRendering=0)},renderCanvas:function(t,e){var i=this.viewportTransform,n=this.clipPath;this.cancelRequestedRender(),this.calcViewportBoundaries(),this.clearContext(t),b.util.setImageSmoothing(t,this.imageSmoothingEnabled),this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),!this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),n&&(n.canvas=this,n.shouldCache(),n._transformDone=!0,n.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t)),this._renderOverlay(t),this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.fire("after:render",{ctx:t})},drawClipPathOnCanvas:function(t){var e=this.viewportTransform,i=this.clipPath;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t.globalCompositeOperation="destination-in",i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},_renderObjects:function(t,e){var i,n;for(i=0,n=e.length;i<n;++i)e[i]&&e[i].render(t)},_renderBackgroundOrOverlay:function(t,e){var i=this[e+"Color"],n=this[e+"Image"],r=this.viewportTransform,s=this[e+"Vpt"];if(i||n){if(i){t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=i.toLive?i.toLive(t,this):i,s&&t.transform(r[0],r[1],r[2],r[3],r[4],r[5]),t.transform(1,0,0,1,i.offsetX||0,i.offsetY||0);var o=i.gradientTransform||i.patternTransform;o&&t.transform(o[0],o[1],o[2],o[3],o[4],o[5]),t.fill(),t.restore()}n&&(t.save(),s&&t.transform(r[0],r[1],r[2],r[3],r[4],r[5]),n.render(t),t.restore())}},_renderBackground:function(t){this._renderBackgroundOrOverlay(t,"background")},_renderOverlay:function(t){this._renderBackgroundOrOverlay(t,"overlay")},getCenter:function(){return{top:this.height/2,left:this.width/2}},getCenterPoint:function(){return new b.Point(this.width/2,this.height/2)},centerObjectH:function(t){return this._centerObject(t,new b.Point(this.getCenterPoint().x,t.getCenterPoint().y))},centerObjectV:function(t){return this._centerObject(t,new b.Point(t.getCenterPoint().x,this.getCenterPoint().y))},centerObject:function(t){var e=this.getCenterPoint();return this._centerObject(t,e)},viewportCenterObject:function(t){var e=this.getVpCenter();return this._centerObject(t,e)},viewportCenterObjectH:function(t){var e=this.getVpCenter();return this._centerObject(t,new b.Point(e.x,t.getCenterPoint().y)),this},viewportCenterObjectV:function(t){var e=this.getVpCenter();return this._centerObject(t,new b.Point(t.getCenterPoint().x,e.y))},getVpCenter:function(){var t=this.getCenterPoint(),e=s(this.viewportTransform);return r(t,e)},_centerObject:function(t,e){return t.setPositionByOrigin(e,"center","center"),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll(),this},toDatalessJSON:function(t){return this.toDatalessObject(t)},toObject:function(t){return this._toObjectMethod("toObject",t)},toDatalessObject:function(t){return this._toObjectMethod("toDatalessObject",t)},_toObjectMethod:function(e,i){var n=this.clipPath,r={version:b.version,objects:this._toObjects(e,i)};return n&&!n.excludeFromExport&&(r.clipPath=this._toObject(this.clipPath,e,i)),t(r,this.__serializeBgOverlay(e,i)),b.util.populateWithProperties(this,r,i),r},_toObjects:function(t,e){return this._objects.filter(function(t){return!t.excludeFromExport}).map(function(i){return this._toObject(i,t,e)},this)},_toObject:function(t,e,i){var n;this.includeDefaultValues||(n=t.includeDefaultValues,t.includeDefaultValues=!1);var r=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=n),r},__serializeBgOverlay:function(t,e){var i={},n=this.backgroundImage,r=this.overlayImage,s=this.backgroundColor,o=this.overlayColor;return s&&s.toObject?s.excludeFromExport||(i.background=s.toObject(e)):s&&(i.background=s),o&&o.toObject?o.excludeFromExport||(i.overlay=o.toObject(e)):o&&(i.overlay=o),n&&!n.excludeFromExport&&(i.backgroundImage=this._toObject(n,t,e)),r&&!r.excludeFromExport&&(i.overlayImage=this._toObject(r,t,e)),i},svgViewportTransformation:!0,toSVG:function(t,e){t||(t={}),t.reviver=e;var i=[];return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push('<g clip-path="url(#'+this.clipPath.clipPathId+')" >\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("</g>\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push("</svg>"),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',r,'" ','height="',s,'" ',o,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",b.version,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"</defs>\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'<clipPath id="'+e.clipPathId+'" >\n'+this.clipPath.toClipPathSVG(t.reviver)+"</clipPath>\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,o,a,h="",l={},c=b.fontPaths,u=[];for(this._objects.forEach(function t(e){u.push(e),e._objects&&e._objects.forEach(t)}),o=0,a=u.length;o<a;o++)if(e=(t=u[o]).fontFamily,-1!==t.type.indexOf("text")&&!l[e]&&c[e]&&(l[e]=!0,t.styles))for(r in i=t.styles)for(s in n=i[r])!l[e=n[s].fontFamily]&&c[e]&&(l[e]=!0);for(var d in l)h+=["\t\t@font-face {\n","\t\t\tfont-family: '",d,"';\n","\t\t\tsrc: url('",c[d],"');\n","\t\t}\n"].join("");return h&&(h=['\t<style type="text/css">',"<![CDATA[\n",h,"]]>","</style>\n"].join("")),h},_setSVGObjects:function(t,e){var i,n,r,s=this._objects;for(n=0,r=s.length;n<r;n++)(i=s[n]).excludeFromExport||this._setSVGObject(t,i,e)},_setSVGObject:function(t,e,i){t.push(e.toSVG(i))},_setSVGBgOverlayImage:function(t,e,i){this[e]&&!this[e].excludeFromExport&&this[e].toSVG&&t.push(this[e].toSVG(i))},_setSVGBgOverlayColor:function(t,e){var i=this[e+"Color"],n=this.viewportTransform,r=this.width,s=this.height;if(i)if(i.toLive){var o=i.repeat,a=b.util.invertTransform(n),h=this[e+"Vpt"]?b.util.matrixToSVG(a):"";t.push('<rect transform="'+h+" translate(",r/2,",",s/2,')"',' x="',i.offsetX-r/2,'" y="',i.offsetY-s/2,'" ','width="',"repeat-y"===o||"no-repeat"===o?i.source.width:r,'" height="',"repeat-x"===o||"no-repeat"===o?i.source.height:s,'" fill="url(#SVGID_'+i.id+')"',"></rect>\n")}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',i,'"',"></rect>\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;e<r.length;e++)n=r[e],i(this._objects,n),this._objects.push(n);else i(this._objects,t),this._objects.push(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},sendBackwards:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(a=h._objects,n=0;n<a.length;n++)r=a[n],(s=this._objects.indexOf(r))>0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,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,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))<this._objects.length-1-l&&(o=s+1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else(s=this._objects.indexOf(t))!==this._objects.length-1&&(o=this._findNewUpperIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewUpperIndex:function(t,e,i){var n,r,s;if(i){for(n=e,r=e+1,s=this._objects.length;r<s;++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},moveTo:function(t,e){return i(this._objects,t),this._objects.splice(e,0,t),this.renderOnAddRemove&&this.requestRenderAll()},dispose:function(){return this.isRendering&&(b.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"),b.util.setStyle(this.lowerCanvasEl,this._originalCanvasStyle),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),b.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},toString:function(){return"#<fabric.Canvas ("+this.complexity()+"): { objects: "+this._objects.length+" }>"}}),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=a();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=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(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<i;e++)this._drawSegment(t,n,r),n=this._points[e],r=this._points[e+1];t.lineTo(n.x,n.y),t.stroke(),t.restore()},convertPointsToSVGPath:function(t){var e=this.width/1e3;return b.util.getSmoothPathFromPoints(t,e)},_isEmptySVGPath:function(t){return"M 0 0 Q 0 0 0 0 L 0 0"===b.util.joinPath(t)},createPath:function(t){var e=new b.Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new b.Shadow(this.shadow)),e},decimatePoints:function(t,e){if(t.length<=2)return t;var i,n=this.canvas.getZoom(),r=Math.pow(e/n,2),s=t.length-1,o=t[0],a=[o];for(i=1;i<s-1;i++)Math.pow(o.x-t[i].x,2)+Math.pow(o.y-t[i].y,2)>=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_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;t<e;t++)this.dot(i,n[t]);i.restore()},onMouseMove:function(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.needsFullRender()?(this.canvas.clearContext(this.canvas.contextTop),this.addPoint(t),this._render()):this.drawDot(t))},onMouseUp:function(){var t,e,i=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;var n=[];for(t=0,e=this.points.length;t<e;t++){var r=this.points[t],s=new b.Circle({radius:r.radius,left:r.x,top:r.y,originX:"center",originY:"center",fill:r.fill});this.shadow&&(s.shadow=new b.Shadow(this.shadow)),n.push(s)}var o=new b.Group(n);o.canvas=this.canvas,this.canvas.fire("before:path:created",{path:o}),this.canvas.add(o),this.canvas.fire("path:created",{path:o}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=i,this.canvas.requestRenderAll()},addPoint:function(t){var e=new b.Point(t.x,t.y),i=b.util.getRandomInt(Math.max(0,this.width-20),this.width+20)/2,n=new b.Color(this.color).setAlpha(b.util.getRandomInt(0,100)/100).toRgba();return e.radius=i,e.fill=n,this.points.push(e),e}}),b.SprayBrush=b.util.createClass(b.BaseBrush,{width:10,density:20,dotWidth:1,dotWidthVariance:1,randomOpacity:!1,optimizeOverlapping:!0,initialize:function(t){this.canvas=t,this.sprayChunks=[]},onMouseDown:function(t){this.sprayChunks.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.render(this.sprayChunkPoints)},onMouseMove:function(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.addSprayChunk(t),this.render(this.sprayChunkPoints))},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],i=0,n=this.sprayChunks.length;i<n;i++)for(var r=this.sprayChunks[i],s=0,o=r.length;s<o;s++){var a=new b.Rect({width:r[s].width,height:r[s].width,left:r[s].x+1,top:r[s].y+1,originX:"center",originY:"center",fill:this.color});e.push(a)}this.optimizeOverlapping&&(e=this._getOptimizedRects(e));var h=new b.Group(e);this.shadow&&h.set("shadow",new b.Shadow(this.shadow)),this.canvas.fire("before:path:created",{path:h}),this.canvas.add(h),this.canvas.fire("path:created",{path:h}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},_getOptimizedRects:function(t){var e,i,n,r={};for(i=0,n=t.length;i<n;i++)r[e=t[i].left+""+t[i].top]||(r[e]=t[i]);var s=[];for(e in r)s.push(r[e]);return s},render:function(t){var e,i,n=this.canvas.contextTop;for(n.fillStyle=this.color,this._saveAndTransform(n),e=0,i=t.length;e<i;e++){var r=t[e];void 0!==r.opacity&&(n.globalAlpha=r.opacity),n.fillRect(r.x,r.y,r.width,r.width)}n.restore()},_render:function(){var t,e,i=this.canvas.contextTop;for(i.fillStyle=this.color,this._saveAndTransform(i),t=0,e=this.sprayChunks.length;t<e;t++)this.render(this.sprayChunks[t]);i.restore()},addSprayChunk:function(t){this.sprayChunkPoints=[];var e,i,n,r,s=this.width/2;for(r=0;r<this.density;r++){e=b.util.getRandomInt(t.x-s,t.x+s),i=b.util.getRandomInt(t.y-s,t.y+s),n=this.dotWidthVariance?b.util.getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth;var o=new b.Point(e,i);o.width=n,this.randomOpacity&&(o.opacity=b.util.getRandomInt(0,100)/100),this.sprayChunkPoints.push(o)}this.sprayChunks.push(this.sprayChunkPoints)}}),b.PatternBrush=b.util.createClass(b.PencilBrush,{getPatternSrc:function(){var t=b.util.createCanvasElement(),e=t.getContext("2d");return t.width=t.height=25,e.fillStyle=this.color,e.beginPath(),e.arc(10,10,10,0,2*Math.PI,!1),e.closePath(),e.fill(),t},getPatternSrcFunction:function(){return String(this.getPatternSrc).replace("this.color",'"'+this.color+'"')},getPattern:function(t){return t.createPattern(this.source||this.getPatternSrc(),"repeat")},_setBrushStyles:function(t){this.callSuper("_setBrushStyles",t),t.strokeStyle=this.getPattern(t)},createPath:function(t){var e=this.callSuper("createPath",t),i=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new b.Pattern({source:this.source||this.getPatternSrcFunction(),offsetX:-i.x,offsetY:-i.y}),e}}),function(){var t=b.util.getPointer,e=b.util.degreesToRadians,i=b.util.isTouchEvent;for(var n in b.Canvas=b.util.createClass(b.StaticCanvas,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e),this._initInteractive(),this._createCacheCanvas()},uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",interactive:!0,selection:!0,selectionKey:"shiftKey",altSelectionKey:null,selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",containerClass:"canvas-container",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,isDrawingMode:!1,preserveObjectStacking:!1,snapAngle:0,snapThreshold:null,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,targets:[],enablePointerEvents:!1,_hoveredTarget:null,_hoveredTargets:[],_initInteractive:function(){this._currentTransform=null,this._groupSelector=null,this._initWrapperElement(),this._createUpperCanvas(),this._initEventListeners(),this._initRetinaScaling(),this.freeDrawingBrush=b.PencilBrush&&new b.PencilBrush(this),this.calcOffset()},_chooseObjectsToRender:function(){var t,e,i,n=this.getActiveObjects();if(n.length>0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r<s;r++)t=this._objects[r],-1===n.indexOf(t)?e.push(t):i.push(t);n.length>1&&(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 o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,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,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,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:l.x,originY:l.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,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,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),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,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],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,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,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{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: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){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,o=!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,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=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[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||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;s<n.length;s++)n[s].fire(t,r);return i},_handleEvent:function(t,e,i,n){var r=this._target,s=this.targets||[],o={e:t,target:r,subTargets:s,button:i||1,isClick:n||!1,pointer:this._pointer,absolutePointer:this._absolutePointer,transform:this._currentTransform};"up"===e&&(o.currentTarget=this.findTarget(t),o.currentSubTargets=this.targets),this.fire("mouse:"+e,o),r&&r.fire("mouse"+e,o);for(var a=0;a<s.length;a++)s[a].fire("mouse"+e,o)},_finalizeCurrentTransform:function(t){var e=this._currentTransform,i=e.target,n={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),(e.actionPerformed||this.stateful&&i.hasStateChanged())&&this._fire("modified",n)},_onMouseDownInDrawingMode:function(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&this.discardActiveObject(t).requestRenderAll();var e=this.getPointer(t);this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down")},_onMouseMoveInDrawingMode:function(t){if(this._isCurrentlyDrawing){var e=this.getPointer(t);this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")},_onMouseUpInDrawingMode:function(t){var e=this.getPointer(t);this._isCurrentlyDrawing=this.freeDrawingBrush.onMouseUp({e:t,pointer:e}),this._handleEvent(t,"up")},__onMouseDown:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"down:before");var e=this._target;if(n(t,3))this.fireRightClick&&this._handleEvent(t,"down",3);else if(n(t,2))this.fireMiddleClick&&this._handleEvent(t,"down",2);else if(this.isDrawingMode)this._onMouseDownInDrawingMode(t);else if(this._isMainEvent(t)&&!this._currentTransform){var i=this._pointer;this._previousPointer=i;var r=this._shouldRender(e),s=this._shouldGroup(t,e);if(this._shouldClearSelection(t,e)?this.discardActiveObject(t):s&&(this._handleGrouping(t,e),e=this._activeObject),!this.selection||e&&(e.selectable||e.isEditing||e===this._activeObject)||(this._groupSelector={ex:this._absolutePointer.x,ey:this._absolutePointer.y,top:0,left:0}),e){var o=e===this._activeObject;e.selectable&&"down"===e.activeOn&&this.setActiveObject(e,t);var a=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t));if(e.__corner=a,e===this._activeObject&&(a||!s)){this._setupCurrentTransform(t,e,o);var h=e.controls[a],l=(i=this.getPointer(t),h&&h.getMouseDownHandler(t,e,h));l&&l(t,this._currentTransform,i.x,i.y)}}this._handleEvent(t,"down"),(r||s)&&this.requestRenderAll()}},_resetTransformEventData:function(){this._target=null,this._pointer=null,this._absolutePointer=null},_cacheTransformEventData:function(t){this._resetTransformEventData(),this._pointer=this.getPointer(t,!0),this._absolutePointer=this.restorePointerVpt(this._pointer),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)||null},_beforeTransform:function(t){var e=this._currentTransform;this.stateful&&e.target.saveState(),this.fire("before:transform",{e:t,transform:e})},__onMouseMove:function(t){var e,i;if(this._handleEvent(t,"move:before"),this._cacheTransformEventData(t),this.isDrawingMode)this._onMouseMoveInDrawingMode(t);else if(this._isMainEvent(t)){var n=this._groupSelector;n?(i=this._absolutePointer,n.left=i.x-n.ex,n.top=i.y-n.ey,this.renderTop()):this._currentTransform?this._transformObject(t):(e=this.findTarget(t)||null,this._setCursorFromEvent(t,e),this._fireOverOutEvents(e,t)),this._handleEvent(t,"move"),this._resetTransformEventData()}},_fireOverOutEvents:function(t,e){var i=this._hoveredTarget,n=this._hoveredTargets,r=this.targets,s=Math.max(n.length,r.length);this.fireSyntheticInOutEvents(t,e,{oldTarget:i,evtOut:"mouseout",canvasEvtOut:"mouse:out",evtIn:"mouseover",canvasEvtIn:"mouse:over"});for(var o=0;o<s;o++)this.fireSyntheticInOutEvents(r[o],e,{oldTarget:n[o],evtOut:"mouseout",evtIn:"mouseover"});this._hoveredTarget=t,this._hoveredTargets=this.targets.concat()},_fireEnterLeaveEvents:function(t,e){var i=this._draggedoverTarget,n=this._hoveredTargets,r=this.targets,s=Math.max(n.length,r.length);this.fireSyntheticInOutEvents(t,e,{oldTarget:i,evtOut:"dragleave",evtIn:"dragenter"});for(var o=0;o<s;o++)this.fireSyntheticInOutEvents(r[o],e,{oldTarget:n[o],evtOut:"dragleave",evtIn:"dragenter"});this._draggedoverTarget=t},fireSyntheticInOutEvents:function(t,e,i){var n,r,s,o=i.oldTarget,a=o!==t,h=i.canvasEvtIn,l=i.canvasEvtOut;a&&(n={e:e,target:t,previousTarget:o},r={e:e,target:o,nextTarget:t}),s=t&&a,o&&a&&(l&&this.fire(l,r),o.fire(i.evtOut,r)),s&&(h&&this.fire(h,n),t.fire(i.evtIn,n))},__onMouseWheel:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()},_transformObject:function(t){var e=this.getPointer(t),i=this._currentTransform;i.reset=!1,i.shiftKey=t.shiftKey,i.altKey=t[this.centeredKey],this._performTransformAction(t,i,e),i.actionPerformed&&this.requestRenderAll()},_performTransformAction:function(t,e,i){var n=i.x,r=i.y,s=e.action,o=!1,a=e.actionHandler;a&&(o=a(t,e,n,r)),"drag"===s&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o},_fire:b.controlsUtils.fireEvent,_setCursorFromEvent:function(t,e){if(!e)return this.setCursor(this.defaultCursor),!1;var i=e.hoverCursor||this.hoverCursor,n=this._activeObject&&"activeSelection"===this._activeObject.type?this._activeObject:null,r=(!n||!n.contains(e))&&e._findTargetCorner(this.getPointer(t,!0));r?this.setCursor(this.getCornerCursor(r,e,t)):(e.subTargetCheck&&this.targets.concat().reverse().map(function(t){i=t.hoverCursor||i}),this.setCursor(i))},getCornerCursor:function(t,e,i){var n=e.controls[t];return n.cursorStyleHandler(i,n,e)}})}(),v=Math.min,y=Math.max,b.util.object.extend(b.Canvas.prototype,{_shouldGroup:function(t,e){var i=this._activeObject;return i&&this._isSelectionKeyPressed(t)&&e&&e.selectable&&this.selection&&(i!==e||"activeSelection"===i.type)&&!e.onSelect({e:t})},_handleGrouping:function(t,e){var i=this._activeObject;i.__corner||(e!==i||(e=this.findTarget(t,!0))&&e.selectable)&&(i&&"activeSelection"===i.type?this._updateActiveSelection(e,t):this._createActiveSelection(e,t))},_updateActiveSelection:function(t,e){var i=this._activeObject,n=i._objects.slice(0);i.contains(t)?(i.removeWithUpdate(t),this._hoveredTarget=t,this._hoveredTargets=this.targets.concat(),1===i.size()&&this._setActiveObject(i.item(0),e)):(i.addWithUpdate(t),this._hoveredTarget=i,this._hoveredTargets=this.targets.concat()),this._fireSelectionEvents(n,e)},_createActiveSelection:function(t,e){var i=this.getActiveObjects(),n=this._createGroup(t);this._hoveredTarget=n,this._setActiveObject(n,e),this._fireSelectionEvents(i,e)},_createGroup:function(t){var e=this._objects,i=e.indexOf(this._activeObject)<e.indexOf(t)?[this._activeObject,t]:[t,this._activeObject];return this._activeObject.isEditing&&this._activeObject.exitEditing(),new b.ActiveSelection(i,{canvas:this})},_groupSelectedObjects:function(t){var e,i=this._collectObjects(t);1===i.length?this.setActiveObject(i[0],t):i.length>1&&(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,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,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,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,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=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,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,o=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,o,e)}):r.__setupCanvas.call(r,n,t,o,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,o=e.util.degreesToRadians,a=!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:a,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,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return n<o&&(t.width=o),r<o&&(t.height=o),t;var a=n/r,h=e.util.limitDimsByArea(a,i),l=e.util.capValue,c=l(o,h.x,s),u=l(o,h.y,s);return n>c&&(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,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==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,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.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?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,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"#<fabric."+s(this.type)+">"},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,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),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(o(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,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*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(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),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(o*this.scaleX/r.zoomX,o*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,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.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(a||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,o(-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 o=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 o(i[s],i):new o(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,o,a,h=t.x,l=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,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},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,o=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+=o*(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,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))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 o in e)if(!((r=e[o]).o.y<t.y&&r.d.y<t.y||r.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)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:0===t?1e-4:t},scale:function(t){return this._set("scaleX",t),this._set("scaleY",t),this.setCoords()},scaleToWidth:function(t,e){var i=this.getBoundingRect(e).width/this.getScaledWidth();return this.scale(t/this.width/i)},scaleToHeight:function(t,e){var i=this.getBoundingRect(e).height/this.getScaledHeight();return this.scale(t/this.height/i)},calcLineCoords:function(){var i=this.getViewportTransform(),r=this.padding,s=e(this.angle),o=t.cos(s)*r,a=t.sin(s)*r,h=o+a,l=o-a,c=this.calcACoords(),u={tl:n(c.tl,i),tr:n(c.tr,i),bl:n(c.bl,i),br:n(c.br,i)};return r&&(u.tl.x-=l,u.tl.y-=h,u.tr.x+=h,u.tr.y-=l,u.bl.x-=h,u.bl.y+=l,u.br.x+=l,u.br.y+=h),u},calcOCoords:function(){var t=this._calcRotateMatrix(),e=this._calcTranslateMatrix(),n=this.getViewportTransform(),r=i(n,e),s=i(r,t),o=(s=i(s,[1/n[0],0,0,1/n[3],0,0]),this._calculateCurrentDimensions()),a={};return this.forEachControl(function(t,e,i){a[e]=t.positionHandler(o,s,i)}),a},calcACoords:function(){var t=this._calcRotateMatrix(),e=this._calcTranslateMatrix(),r=i(e,t),s=this._getTransformedDimensions(),o=s.x/2,a=s.y/2;return{tl:n({x:-o,y:-a},r),tr:n({x:o,y:-a},r),bl:n({x:-o,y:a},r),br:n({x:o,y:a},r)}},setCoords:function(t){return this.aCoords=this.calcACoords(),this.lineCoords=this.group?this.aCoords:this.calcLineCoords(),t||(this.oCoords=this.calcOCoords(),this._setCornerCoords&&this._setCornerCoords()),this},_calcRotateMatrix:function(){return t.calcRotateMatrix(this)},_calcTranslateMatrix:function(){var t=this.getCenterPoint();return[1,0,0,1,t.x,t.y]},transformMatrixKey:function(t){var e="_",i="";return!t&&this.group&&(i=this.group.transformMatrixKey(t)+e),i+this.top+e+this.left+e+this.scaleX+e+this.scaleY+e+this.skewX+e+this.skewY+e+this.angle+e+this.originX+e+this.originY+e+this.width+e+this.height+e+this.strokeWidth+this.flipX+this.flipY},calcTransformMatrix:function(t){var e=this.calcOwnMatrix();if(t||!this.group)return e;var n=this.transformMatrixKey(t),r=this.matrixCache||(this.matrixCache={});return r.key===n?r.value:(this.group&&(e=i(this.group.calcTransformMatrix(!1),e)),r.key=n,r.value=e,e)},calcOwnMatrix:function(){var e=this.transformMatrixKey(!0),i=this.ownMatrixCache||(this.ownMatrixCache={});if(i.key===e)return i.value;var n=this._calcTranslateMatrix(),r={angle:this.angle,translateX:n[4],translateY:n[5],scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY};return i.key=e,i.value=t.composeMatrix(r),i.value},_getNonTransformedDimensions:function(){var t=this.strokeWidth;return{x:this.width+t,y:this.height+t}},_getTransformedDimensions:function(e,i){void 0===e&&(e=this.skewX),void 0===i&&(i=this.skewY);var n,r,s,o=0===e&&0===i;if(this.strokeUniform?(r=this.width,s=this.height):(r=(n=this._getNonTransformedDimensions()).x,s=n.y),o)return this._finalizeDimensions(r*this.scaleX,s*this.scaleY);var a=t.sizeAfterTransform(r,s,{scaleX:this.scaleX,scaleY:this.scaleY,skewX:e,skewY:i});return this._finalizeDimensions(a.x,a.y)},_finalizeDimensions:function(t,e){return this.strokeUniform?{x:t+this.strokeWidth,y:e+this.strokeWidth}:{x:t,y:e}},_calculateCurrentDimensions:function(){var t=this.getViewportTransform(),e=this._getTransformedDimensions();return n(e,t,!0).scalarAdd(2*this.padding)}})}(),b.util.object.extend(b.Object.prototype,{sendToBack:function(){return this.group?b.StaticCanvas.prototype.sendToBack.call(this.group,this):this.canvas&&this.canvas.sendToBack(this),this},bringToFront:function(){return this.group?b.StaticCanvas.prototype.bringToFront.call(this.group,this):this.canvas&&this.canvas.bringToFront(this),this},sendBackwards:function(t){return this.group?b.StaticCanvas.prototype.sendBackwards.call(this.group,this,t):this.canvas&&this.canvas.sendBackwards(this,t),this},bringForward:function(t){return this.group?b.StaticCanvas.prototype.bringForward.call(this.group,this,t):this.canvas&&this.canvas.bringForward(this,t),this},moveTo:function(t){return this.group&&"activeSelection"!==this.group.type?b.StaticCanvas.prototype.moveTo.call(this.group,this,t):this.canvas&&this.canvas.moveTo(this,t),this}}),function(){function t(t,e){if(e){if(e.toLive)return t+": url(#SVGID_"+e.id+"); ";var i=new b.Color(e),n=t+": "+i.toRgb()+"; ",r=i.getAlpha();return 1!==r&&(n+=t+"-opacity: "+r.toString()+"; "),n}return t+": none; "}var e=b.util.toFixed;b.util.object.extend(b.Object.prototype,{getSvgStyles:function(e){var i=this.fillRule?this.fillRule:"nonzero",n=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):"none",s=this.strokeDashOffset?this.strokeDashOffset:"0",o=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=void 0!==this.opacity?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=e?"":this.getSvgFilter(),d=t("fill",this.fill);return[t("stroke",this.stroke),"stroke-width: ",n,"; ","stroke-dasharray: ",r,"; ","stroke-linecap: ",o,"; ","stroke-dashoffset: ",s,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",i,"; ","opacity: ",l,";",u,c].join("")},getSvgSpanStyles:function(e,i){var n="; ",r=e.fontFamily?"font-family: "+(-1===e.fontFamily.indexOf("'")&&-1===e.fontFamily.indexOf('"')?"'"+e.fontFamily+"'":e.fontFamily)+n:"",s=e.strokeWidth?"stroke-width: "+e.strokeWidth+n:"",o=e.fontSize?"font-size: "+e.fontSize+"px"+n:"",a=e.fontStyle?"font-style: "+e.fontStyle+n:"",h=e.fontWeight?"font-weight: "+e.fontWeight+n:"",l=e.fill?t("fill",e.fill):"",c=e.stroke?t("stroke",e.stroke):"",u=this.getSvgTextDecoration(e);return u&&(u="text-decoration: "+u+n),[c,s,r,o,a,h,u,l,e.deltaY?"baseline-shift: "+-e.deltaY+"; ":"",i?"white-space: pre; ":""].join("")},getSvgTextDecoration:function(t){return["overline","underline","line-through"].filter(function(e){return t[e.replace("-","")]}).join(" ")},getSvgFilter:function(){return this.shadow?"filter: url(#SVGID_"+this.shadow.id+");":""},getSvgCommons:function(){return[this.id?'id="'+this.id+'" ':"",this.clipPath?'clip-path="url(#'+this.clipPath.clipPathId+')" ':""].join("")},getSvgTransform:function(t,e){var i=t?this.calcTransformMatrix():this.calcOwnMatrix();return'transform="'+b.util.matrixToSVG(i)+(e||"")+'" '},_setSVGBg:function(t){if(this.backgroundColor){var i=b.Object.NUM_FRACTION_DIGITS;t.push("\t\t<rect ",this._getFillAttributes(this.backgroundColor),' x="',e(-this.width/2,i),'" y="',e(-this.height/2,i),'" width="',e(this.width,i),'" height="',e(this.height,i),'"></rect>\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,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='<clipPath id="'+h.clipPathId+'" >\n'+h.toClipPathSVG(s)+"</clipPath>\n"),c&&g.push("<g ",a,this.getSvgCommons()," >\n"),g.push("<g ",this.getSvgTransform(!1),c?"":a+this.getSvgCommons()," >\n"),i=[o,l,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)),h&&g.push(n),g.push(t.join("")),g.push("</g>\n"),c&&g.push("</g>\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<s;r++)if(!n(t[r],e[r]))return!1;return!0}if(t&&"object"==typeof t){var o,a=Object.keys(t);if(!e||"object"!=typeof e||!i&&a.length!==Object.keys(e).length)return!1;for(r=0,s=a.length;r<s;r++)if("canvas"!==(o=a[r])&&"group"!==o&&!n(t[o],e[o]))return!1;return!0}}b.util.object.extend(b.Object.prototype,{hasStateChanged:function(t){var i="_"+(t=t||e);return Object.keys(this[i]).length<this[t].length||!n(this[i],this,!0)},saveState:function(t){var n=t&&t.propertySet||e,r="_"+n;return this[r]?(i(this,r,this[n]),t&&t.stateProperties&&i(this,r,t.stateProperties),this):this.setupState(t)},setupState:function(t){var i=(t=t||{}).propertySet||e;return t.propertySet=i,this["_"+i]={},this.saveState(t),this}})}(),function(){var t=b.util.degreesToRadians;b.util.object.extend(b.Object.prototype,{_findTargetCorner:function(t,e){if(!this.hasControls||this.group||!this.canvas||this.canvas._activeObject!==this)return!1;var i,n,r,s=t.x,o=t.y,a=Object.keys(this.oCoords),h=a.length-1;for(this.__corner=0;h>=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},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,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!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),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&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,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),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,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),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<s;r++)t=i[r],e=r!==s-1,n.push(this._animate(t,arguments[0][t],arguments[1],e));return n}return this._animate.apply(this,arguments)},_animate:function(t,e,i,n){var r,s=this;e=e.toString(),i=i?b.util.object.clone(i):{},~t.indexOf(".")&&(r=t.split("."));var o=s.colorProperties.indexOf(t)>-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={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,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),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,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h: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["<line ","COMMON_PARTS",'x1="',t.x1,'" y1="',t.y1,'" x2="',t.x2,'" y2="',t.y2,'" />\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),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,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=["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',this.radius,'" />\n'];else{var r=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['<path d="M '+e.util.cos(r)*o+" "+e.util.sin(r)*o," A "+o+" "+o," 0 ",+(n>180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"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["<polygon ","COMMON_PARTS",'points="',[-t+" "+e,"0 "+-e,t+" "+e].join(","),'" />']}}),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["<ellipse ","COMMON_PARTS",'cx="0" cy="0" ','rx="',this.rx,'" ry="',this.ry,'" />\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,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["<rect ","COMMON_PARTS",'x="',-this.width/2,'" y="',-this.height/2,'" rx="',this.rx,'" ry="',this.ry,'" width="',this.width,'" height="',this.height,'" />\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 o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},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,o=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 o(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,o=0,a=this.points.length;o<a;o++)t.push(s(this.points[o].x-i,r),",",s(this.points[o].y-n,r)," ");return["<"+this.type+" ","COMMON_PARTS",'points="',t.join(""),'" />\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<i;s++)e=this.points[s],t.lineTo(e.x-n,e.y-r);return!0},_render:function(t){this.commonRender(t)&&this._renderPaintInOrder(t)},complexity:function(){return this.get("points").length}}),e.Polyline.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polyline.fromElementGenerator=function(t){return function(n,r,s){if(!n)return r(null);s||(s={});var o=e.parsePointsAttribute(n.getAttribute("points")),a=e.parseAttributes(n,e[t].ATTRIBUTE_NAMES);a.fromSVG=!0,r(new e[t](o,i(a,s)))}},e.Polyline.fromElement=e.Polyline.fromElementGenerator("Polyline"),e.Polyline.fromObject=function(t,i){return e.Object._fromObject("Polyline",t,i,"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.projectStrokeOnPoints;e.Polygon?e.warn("fabric.Polygon is already defined"):(e.Polygon=e.util.createClass(e.Polyline,{type:"polygon",_projectStrokeOnPoints:function(){return i(this.points,this)},_render:function(t){this.commonRender(t)&&(t.closePath(),this._renderPaintInOrder(t))}}),e.Polygon.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polygon.fromElement=e.Polyline.fromElementGenerator("Polygon"),e.Polygon.fromObject=function(t,i){e.Object._fromObject("Polygon",t,i,"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.array.min,n=e.util.array.max,r=e.util.object.extend,s=e.util.object.clone,o=e.util.toFixed;e.Path?e.warn("fabric.Path is already defined"):(e.Path=e.util.createClass(e.Object,{type:"path",path:null,cacheProperties:e.Object.prototype.cacheProperties.concat("path","fillRule"),stateProperties:e.Object.prototype.stateProperties.concat("path"),initialize:function(t,e){delete(e=s(e||{})).path,this.callSuper("initialize",e),this._setPath(t||[],e)},_setPath:function(t,i){this.path=e.util.makePathSimpler(Array.isArray(t)?t:e.util.parsePath(t)),e.Polyline.prototype._setPositionDimensions.call(this,i||{})},_renderPathCommands:function(t){var e,i=0,n=0,r=0,s=0,o=0,a=0,h=-this.pathOffset.x,l=-this.pathOffset.y;t.beginPath();for(var c=0,u=this.path.length;c<u;++c)switch((e=this.path[c])[0]){case"L":r=e[1],s=e[2],t.lineTo(r+h,s+l);break;case"M":i=r=e[1],n=s=e[2],t.moveTo(r+h,s+l);break;case"C":r=e[5],s=e[6],o=e[3],a=e[4],t.bezierCurveTo(e[1]+h,e[2]+l,o+h,a+l,r+h,s+l);break;case"Q":t.quadraticCurveTo(e[1]+h,e[2]+l,e[3]+h,e[4]+l),r=e[3],s=e[4],o=e[1],a=e[2];break;case"z":case"Z":r=i,s=n,t.closePath()}},_render:function(t){this._renderPathCommands(t),this._renderPaintInOrder(t)},toString:function(){return"#<fabric.Path ("+this.complexity()+'): { "top": '+this.top+', "left": '+this.left+" }>"},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["<path ","COMMON_PARTS",'d="',e.util.joinPath(this.path),'" stroke-linecap="round" ',"/>\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-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=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u<d;++u){switch((t=this.path[u])[0]){case"L":l=t[1],c=t[2],r=[];break;case"M":a=l=t[1],h=c=t[2],r=[];break;case"C":r=e.util.getBoundsOfCurve(l,c,t[1],t[2],t[3],t[4],t[5],t[6]),l=t[5],c=t[6];break;case"Q":r=e.util.getBoundsOfCurve(l,c,t[1],t[2],t[1],t[2],t[3],t[4]),l=t[3],c=t[4];break;case"z":case"Z":l=a,c=h}r.forEach(function(t){s.push(t.x),o.push(t.y)}),s.push(l),o.push(c)}var f=i(s)||0,g=i(o)||0;return{left:f,top:g,width:(n(s)||0)-f,height:(n(o)||0)-g}}}),e.Path.fromObject=function(t,i){if("string"==typeof t.sourcePath){var n=t.sourcePath;e.loadSVGFromURL(n,function(e){var n=e[0];n.setOptions(t),i&&i(n)})}else e.Object._fromObject("Path",t,i,"path")},e.Path.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(["d"]),e.Path.fromElement=function(t,i,n){var s=e.parseAttributes(t,e.Path.ATTRIBUTE_NAMES);s.fromSVG=!0,i(new e.Path(s.d,r(s,n)))})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.array.min,n=e.util.array.max;e.Group||(e.Group=e.util.createClass(e.Object,e.Collection,{type:"group",strokeWidth:0,subTargetCheck:!1,cacheProperties:[],useSetOnGroup:!1,initialize:function(t,e,i){e=e||{},this._objects=[],i&&this.callSuper("initialize",e),this._objects=t||[];for(var n=this._objects.length;n--;)this._objects[n].group=this;if(i)this._updateObjectsACoords();else{var r=e&&e.centerPoint;void 0!==e.originX&&(this.originX=e.originX),void 0!==e.originY&&(this.originY=e.originY),r||this._calcBounds(),this._updateObjectsCoords(r),delete e.centerPoint,this.callSuper("initialize",e)}this.setCoords()},_updateObjectsACoords:function(){for(var t=this._objects.length;t--;)this._objects[t].setCoords(!0)},_updateObjectsCoords:function(t){t=t||this.getCenterPoint();for(var e=this._objects.length;e--;)this._updateObjectCoords(this._objects[e],t)},_updateObjectCoords:function(t,e){var i=t.left,n=t.top;t.set({left:i-e.x,top:n-e.y}),t.group=this,t.setCoords(!0)},toString:function(){return"#<fabric.Group: ("+this.complexity()+")>"},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++)if(this._objects[i].willDrawShadow())return this.ownCaching=!1,!1;return t},willDrawShadow:function(){if(e.Object.prototype.willDrawShadow.call(this))return!0;for(var t=0,i=this._objects.length;t<i;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return this.ownCaching||this.group&&this.group.isOnACache()},drawObject:function(t){for(var e=0,i=this._objects.length;e<i;e++)this._objects[e].render(t);this._drawClipPath(t,this.clipPath)},isCacheDirty:function(t){if(this.callSuper("isCacheDirty",t))return!0;if(!this.statefullCache)return!1;for(var e=0,i=this._objects.length;e<i;e++)if(this._objects[e].isCacheDirty(!0)){if(this._cacheCanvas){var n=this.cacheWidth/this.zoomX,r=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-n/2,-r/2,n,r)}return!0}return!1},_restoreObjectsState:function(){var t=this.calcOwnMatrix();return this._objects.forEach(function(i){e.util.addTransformToObject(i,t),delete i.group,i.setCoords()}),this},destroy:function(){return this._objects.forEach(function(t){t.set("dirty",!0)}),this._restoreObjectsState()},dispose:function(){this.callSuper("dispose"),this.forEachObject(function(t){t.dispose&&t.dispose()}),this._objects=[]},toActiveSelection:function(){if(this.canvas){var t=this._objects,i=this.canvas;this._objects=[];var n=this.toObject();delete n.objects;var r=new e.ActiveSelection([]);return r.set(n),r.type="activeSelection",i.remove(this),t.forEach(function(t){t.group=r,t.dirty=!0,i.add(t)}),r.canvas=i,r._objects=t,i._activeObject=r,r.setCoords(),r}},ungroupOnCanvas:function(){return this._restoreObjectsState()},setObjectsCoords:function(){return this.forEachObject(function(t){t.setCoords(!0)}),this},_calcBounds:function(t){for(var e,i,n,r,s=[],o=[],a=["tr","br","bl","tl"],h=0,l=this._objects.length,c=a.length;h<l;++h){for(n=(e=this._objects[h]).calcACoords(),r=0;r<c;r++)i=a[r],s.push(n[i].x),o.push(n[i].y);e.aCoords=n}this._getBounds(s,o,t)},_getBounds:function(t,r,s){var o=new e.Point(i(t),i(r)),a=new e.Point(n(t),n(r)),h=o.y||0,l=o.x||0,c=a.x-o.x||0,u=a.y-o.y||0;this.width=c,this.height=u,s||this.setPositionByOrigin({x:l,y:h},"left","top")},_toSVG:function(t){for(var e=["<g ","COMMON_PARTS"," >\n"],i=0,n=this._objects.length;i<n;i++)e.push("\t\t",this._objects[i].toSVG(t));return e.push("</g>\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<n;i++)e.push("\t",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}}),e.Group.fromObject=function(t,i){var n=t.objects,r=e.util.object.clone(t,!0);delete r.objects,"string"!=typeof n?e.util.enlivenObjects(n,function(n){var r=e.util.object.clone(t,!0);delete r.objects,e.util.enlivenObjectEnlivables(t,r,function(){i&&i(new e.Group(n,r,!0))})}):e.loadSVGFromURL(n,function(s){var o=e.util.groupSVGElements(s,t,n);o.set(r),i&&i(o)})})}(e),function(t){var e=t.fabric||(t.fabric={});e.ActiveSelection||(e.ActiveSelection=e.util.createClass(e.Group,{type:"activeSelection",initialize:function(t,i){i=i||{},this._objects=t||[];for(var n=this._objects.length;n--;)this._objects[n].group=this;i.originX&&(this.originX=i.originX),i.originY&&(this.originY=i.originY),this._calcBounds(),this._updateObjectsCoords(),e.Object.prototype.initialize.call(this,i),this.setCoords()},toGroup:function(){var t=this._objects.concat();this._objects=[];var i=e.Object.prototype.toObject.call(this),n=new e.Group([]);if(delete i.type,n.set(i),t.forEach(function(t){t.canvas.remove(t),t.group=n}),n._objects=t,!this.canvas)return n;var r=this.canvas;return r.add(n),r._activeObject=n,n.setCoords(),n},onDeselect:function(){return this.destroy(),!1},toString:function(){return"#<fabric.ActiveSelection: ("+this.complexity()+")>"},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<r;n++)this._objects[n]._renderControls(t,i);t.restore()}}),e.ActiveSelection.fromObject=function(t,i){e.util.enlivenObjects(t.objects,function(n){delete t.objects,i&&i(new e.ActiveSelection(n,t,!0))})})}(e),function(t){var e=b.util.object.extend;t.fabric||(t.fabric={}),t.fabric.Image?b.warn("fabric.Image is already defined."):(b.Image=b.util.createClass(b.Object,{type:"image",strokeWidth:0,srcFromAttribute:!1,_lastScaleX:1,_lastScaleY:1,_filterScalingX:1,_filterScalingY:1,minimumScaleTrigger:.5,stateProperties:b.Object.prototype.stateProperties.concat("cropX","cropY"),cacheProperties:b.Object.prototype.cacheProperties.concat("cropX","cropY"),cacheKey:"",cropX:0,cropY:0,imageSmoothing:!0,initialize:function(t,e){e||(e={}),this.filters=[],this.cacheKey="texture"+b.Object.__uid++,this.callSuper("initialize",e),this._initElement(t,e)},getElement:function(){return this._element||{}},setElement:function(t,e){return this.removeTexture(this.cacheKey),this.removeTexture(this.cacheKey+"_filtered"),this._element=t,this._originalElement=t,this._initConfig(e),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters(),this},removeTexture:function(t){var e=b.filterBackend;e&&e.evictCachesForKey&&e.evictCachesForKey(t)},dispose:function(){this.callSuper("dispose"),this.removeTexture(this.cacheKey),this.removeTexture(this.cacheKey+"_filtered"),this._cacheContext=void 0,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this))},getCrossOrigin:function(){return this._originalElement&&(this._originalElement.crossOrigin||null)},getOriginalSize:function(){var t=this.getElement();return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}},_stroke:function(t){if(this.stroke&&0!==this.strokeWidth){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}},toObject:function(t){var i=[];this.filters.forEach(function(t){t&&i.push(t.toObject())});var n=e(this.callSuper("toObject",["cropX","cropY"].concat(t)),{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:i});return this.resizeFilter&&(n.resizeFilter=this.resizeFilter.toObject()),n},hasCrop:function(){return this.cropX||this.cropY||this.width<this._element.width||this.height<this._element.height},_toSVG:function(){var t,e=[],i=[],n=this._element,r=-this.width/2,s=-this.height/2,o="",a="";if(!n)return[];if(this.hasCrop()){var h=b.Object.__uid++;e.push('<clipPath id="imageCrop_'+h+'">\n','\t<rect x="'+r+'" y="'+s+'" width="'+this.width+'" height="'+this.height+'" />\n',"</clipPath>\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t<image ","COMMON_PARTS",'xlink:href="',this.getSvgSrc(!0),'" x="',r-this.cropX,'" y="',s-this.cropY,'" width="',n.width||n.naturalWidth,'" height="',n.height||n.height,a,'"',o,"></image>\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t<rect ",'x="',r,'" y="',s,'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'"/>\n'],this.fill=l}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'#<fabric.Image: { src: "'+this.getSrc()+'" }>'},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 o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.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,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);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(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,o=0,a=0,h=0,l=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=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),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"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];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 o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,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 o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),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)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},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 o={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(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),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 o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},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,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s<a;s+=4)e=o[s],i=o[s+1],n=o[s+2],l?(o[s]=e*h[0]+i*h[1]+n*h[2]+255*h[4],o[s+1]=e*h[5]+i*h[6]+n*h[7]+255*h[9],o[s+2]=e*h[10]+i*h[11]+n*h[12]+255*h[14]):(r=o[s+3],o[s]=e*h[0]+i*h[1]+n*h[2]+r*h[3]+255*h[4],o[s+1]=e*h[5]+i*h[6]+n*h[7]+r*h[8]+255*h[9],o[s+2]=e*h[10]+i*h[11]+n*h[12]+r*h[13]+255*h[14],o[s+3]=e*h[15]+i*h[16]+n*h[17]+r*h[18]+255*h[19])},getUniformLocations:function(t,e){return{uColorMatrix:t.getUniformLocation(e,"uColorMatrix"),uConstants:t.getUniformLocation(e,"uConstants")}},sendUniformData:function(t,e){var i=this.matrix,n=[i[0],i[1],i[2],i[3],i[5],i[6],i[7],i[8],i[10],i[11],i[12],i[13],i[15],i[16],i[17],i[18]],r=[i[4],i[9],i[14],i[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,n),t.uniform4fv(e.uConstants,r)}}),e.Image.filters.ColorMatrix.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Brightness=n(i.BaseFilter,{type:"Brightness",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBrightness;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += uBrightness;\ngl_FragColor = color;\n}",brightness:0,mainParameter:"brightness",applyTo2d:function(t){if(0!==this.brightness){var e,i=t.imageData.data,n=i.length,r=Math.round(255*this.brightness);for(e=0;e<n;e+=4)i[e]=i[e]+r,i[e+1]=i[e+1]+r,i[e+2]=i[e+2]+r}},getUniformLocations:function(t,e){return{uBrightness:t.getUniformLocation(e,"uBrightness")}},sendUniformData:function(t,e){t.uniform1f(e.uBrightness,this.brightness)}}),e.Image.filters.Brightness.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,r=e.util.createClass;n.Convolute=r(n.BaseFilter,{type:"Convolute",opaque:!1,matrix:[0,0,0,0,1,0,0,0,0],fragmentSource:{Convolute_3_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_3_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_5_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_5_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_7_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_7_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_9_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_9_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}"},retrieveShader:function(t){var e=Math.sqrt(this.matrix.length),i=this.type+"_"+e+"_"+(this.opaque?1:0),n=this.fragmentSource[i];return t.programCache.hasOwnProperty(i)||(t.programCache[i]=this.createProgram(t.context,n)),t.programCache[i]},applyTo2d:function(t){var e,i,n,r,s,o,a,h,l,c,u,d,f,g=t.imageData,m=g.data,p=this.matrix,_=Math.round(Math.sqrt(p.length)),v=Math.floor(_/2),y=g.width,w=g.height,C=t.ctx.createImageData(y,w),E=C.data,S=this.opaque?1:0;for(u=0;u<w;u++)for(c=0;c<y;c++){for(s=4*(u*y+c),e=0,i=0,n=0,r=0,f=0;f<_;f++)for(d=0;d<_;d++)o=c+d-v,(a=u+f-v)<0||a>=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));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;e<r;e+=4)"average"===s?i=(n[e]+n[e+1]+n[e+2])/3:"lightness"===s?i=(Math.min(n[e],n[e+1],n[e+2])+Math.max(n[e],n[e+1],n[e+2]))/2:"luminosity"===s&&(i=.21*n[e]+.72*n[e+1]+.07*n[e+2]),n[e]=i,n[e+1]=i,n[e+2]=i},retrieveShader:function(t){var e=this.type+"_"+this.mode;if(!t.programCache.hasOwnProperty(e)){var i=this.fragmentSource[this.mode];t.programCache[e]=this.createProgram(t.context,i)}return t.programCache[e]},getUniformLocations:function(t,e){return{uMode:t.getUniformLocation(e,"uMode")}},sendUniformData:function(t,e){t.uniform1i(e.uMode,1)},isNeutralState:function(){return!1}}),e.Image.filters.Grayscale.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Invert=n(i.BaseFilter,{type:"Invert",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uInvert;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nif (uInvert == 1) {\ngl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n} else {\ngl_FragColor = color;\n}\n}",invert:!0,mainParameter:"invert",applyTo2d:function(t){var e,i=t.imageData.data,n=i.length;for(e=0;e<n;e+=4)i[e]=255-i[e],i[e+1]=255-i[e+1],i[e+2]=255-i[e+2]},isNeutralState:function(){return!this.invert},getUniformLocations:function(t,e){return{uInvert:t.getUniformLocation(e,"uInvert")}},sendUniformData:function(t,e){t.uniform1i(e.uInvert,this.invert)}}),e.Image.filters.Invert.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,r=e.util.createClass;n.Noise=r(n.BaseFilter,{type:"Noise",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uStepH;\nuniform float uNoise;\nuniform float uSeed;\nvarying vec2 vTexCoord;\nfloat rand(vec2 co, float seed, float vScale) {\nreturn fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n}\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\ngl_FragColor = color;\n}",mainParameter:"noise",noise:0,applyTo2d:function(t){if(0!==this.noise){var e,i,n=t.imageData.data,r=n.length,s=this.noise;for(e=0,r=n.length;e<r;e+=4)i=(.5-Math.random())*s,n[e]+=i,n[e+1]+=i,n[e+2]+=i}},getUniformLocations:function(t,e){return{uNoise:t.getUniformLocation(e,"uNoise"),uSeed:t.getUniformLocation(e,"uSeed")}},sendUniformData:function(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())},toObject:function(){return i(this.callSuper("toObject"),{noise:this.noise})}}),e.Image.filters.Noise.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Pixelate=n(i.BaseFilter,{type:"Pixelate",blocksize:4,mainParameter:"blocksize",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBlocksize;\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nfloat blockW = uBlocksize * uStepW;\nfloat blockH = uBlocksize * uStepW;\nint posX = int(vTexCoord.x / blockW);\nint posY = int(vTexCoord.y / blockH);\nfloat fposX = float(posX);\nfloat fposY = float(posY);\nvec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\nvec4 color = texture2D(uTexture, squareCoords);\ngl_FragColor = color;\n}",applyTo2d:function(t){var e,i,n,r,s,o,a,h,l,c,u,d=t.imageData,f=d.data,g=d.height,m=d.width;for(i=0;i<g;i+=this.blocksize)for(n=0;n<m;n+=this.blocksize)for(r=f[e=4*i*m+4*n],s=f[e+1],o=f[e+2],a=f[e+3],c=Math.min(i+this.blocksize,g),u=Math.min(n+this.blocksize,m),h=i;h<c;h++)for(l=n;l<u;l++)f[e=4*h*m+4*l]=r,f[e+1]=s,f[e+2]=o,f[e+3]=a},isNeutralState:function(){return 1===this.blocksize},getUniformLocations:function(t,e){return{uBlocksize:t.getUniformLocation(e,"uBlocksize"),uStepW:t.getUniformLocation(e,"uStepW"),uStepH:t.getUniformLocation(e,"uStepH")}},sendUniformData:function(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}),e.Image.filters.Pixelate.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,r=e.util.createClass;n.RemoveColor=r(n.BaseFilter,{type:"RemoveColor",color:"#FFFFFF",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\ngl_FragColor.a = 0.0;\n}\n}",distance:.02,useAlpha:!1,applyTo2d:function(t){var i,n,r,s,o=t.imageData.data,a=255*this.distance,h=new e.Color(this.color).getSource(),l=[h[0]-a,h[1]-a,h[2]-a],c=[h[0]+a,h[1]+a,h[2]+a];for(i=0;i<o.length;i+=4)n=o[i],r=o[i+1],s=o[i+2],n>l[0]&&r>l[1]&&s>l[2]&&n<c[0]&&r<c[1]&&s<c[2]&&(o[i+3]=0)},getUniformLocations:function(t,e){return{uLow:t.getUniformLocation(e,"uLow"),uHigh:t.getUniformLocation(e,"uHigh")}},sendUniformData:function(t,i){var n=new e.Color(this.color).getSource(),r=parseFloat(this.distance),s=[0+n[0]/255-r,0+n[1]/255-r,0+n[2]/255-r,1],o=[n[0]/255+r,n[1]/255+r,n[2]/255+r,1];t.uniform4fv(i.uLow,s),t.uniform4fv(i.uHigh,o)},toObject:function(){return i(this.callSuper("toObject"),{color:this.color,distance:this.distance})}}),e.Image.filters.RemoveColor.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass,r={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]};for(var s in r)i[s]=n(i.ColorMatrix,{type:s,matrix:r[s],mainParameter:!1,colorsOnly:!0}),e.Image.filters[s].fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric,i=e.Image.filters,n=e.util.createClass;i.BlendColor=n(i.BaseFilter,{type:"BlendColor",color:"#F95C63",mode:"multiply",alpha:1,fragmentSource:{multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",diff:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"if (uColor.r < 0.5) {\ngl_FragColor.r *= 2.0 * uColor.r;\n} else {\ngl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n}\nif (uColor.g < 0.5) {\ngl_FragColor.g *= 2.0 * uColor.g;\n} else {\ngl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n}\nif (uColor.b < 0.5) {\ngl_FragColor.b *= 2.0 * uColor.b;\n} else {\ngl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n}\n",tint:"gl_FragColor.rgb *= (1.0 - uColor.a);\ngl_FragColor.rgb += uColor.rgb;\n"},buildSource:function(t){return"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ngl_FragColor = color;\nif (color.a > 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,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d<c;d+=4)switch(s=l[d],o=l[d+1],a=l[d+2],this.mode){case"multiply":l[d]=s*i/255,l[d+1]=o*n/255,l[d+2]=a*r/255;break;case"screen":l[d]=255-(255-s)*(255-i)/255,l[d+1]=255-(255-o)*(255-n)/255,l[d+2]=255-(255-a)*(255-r)/255;break;case"add":l[d]=s+i,l[d+1]=o+n,l[d+2]=a+r;break;case"diff":case"difference":l[d]=Math.abs(s-i),l[d+1]=Math.abs(o-n),l[d+2]=Math.abs(a-r);break;case"subtract":l[d]=s-i,l[d+1]=o-n,l[d+2]=a-r;break;case"darken":l[d]=Math.min(s,i),l[d+1]=Math.min(o,n),l[d+2]=Math.min(a,r);break;case"lighten":l[d]=Math.max(s,i),l[d+1]=Math.max(o,n),l[d+2]=Math.max(a,r);break;case"overlay":l[d]=i<128?2*s*i/255:255-2*(255-s)*(255-i)/255,l[d+1]=n<128?2*o*n/255:255-2*(255-o)*(255-n)/255,l[d+2]=r<128?2*a*r/255:255-2*(255-a)*(255-r)/255;break;case"exclusion":l[d]=i+s-2*i*s/255,l[d+1]=n+o-2*n*o/255,l[d+2]=r+a-2*r*a/255;break;case"tint":l[d]=i+s*u,l[d+1]=n+o*u,l[d+2]=r+a*u}},getUniformLocations:function(t,e){return{uColor:t.getUniformLocation(e,"uColor")}},sendUniformData:function(t,i){var n=new e.Color(this.color).getSource();n[0]=this.alpha*n[0]/255,n[1]=this.alpha*n[1]/255,n[2]=this.alpha*n[2]/255,n[3]=this.alpha,t.uniform4fv(i.uColor,n)},toObject:function(){return{type:this.type,color:this.color,mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendColor.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric,i=e.Image.filters,n=e.util.createClass;i.BlendImage=n(i.BaseFilter,{type:"BlendImage",image:null,mode:"multiply",alpha:1,vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nuniform mat3 uTransformMatrix;\nvoid main() {\nvTexCoord = aPosition;\nvTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.rgba *= color2.rgba;\ngl_FragColor = color;\n}",mask:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.a = color2.a;\ngl_FragColor = color;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,i=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,i)),t.programCache[e]},applyToWebGL:function(t){var e=t.context,i=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,i,e.TEXTURE1),this.callSuper("applyToWebGL",t),this.unbindAdditionalTexture(e,e.TEXTURE1)},createTexture:function(t,e){return t.getCachedTexture(e.cacheKey,e._element)},calculateMatrix:function(){var t=this.image,e=t._element.width,i=t._element.height;return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/i,1]},applyTo2d:function(t){var i,n,r,s,o,a,h,l,c,u,d,f=t.imageData,g=t.filterBackend.resources,m=f.data,p=m.length,_=f.width,v=f.height,y=this.image;g.blendImage||(g.blendImage=e.util.createCanvasElement()),u=(c=g.blendImage).getContext("2d"),c.width!==_||c.height!==v?(c.width=_,c.height=v):u.clearRect(0,0,_,v),u.setTransform(y.scaleX,0,0,y.scaleY,y.left,y.top),u.drawImage(y._element,0,0,_,v),d=u.getImageData(0,0,_,v).data;for(var w=0;w<p;w+=4)switch(o=m[w],a=m[w+1],h=m[w+2],l=m[w+3],i=d[w],n=d[w+1],r=d[w+2],s=d[w+3],this.mode){case"multiply":m[w]=o*i/255,m[w+1]=a*n/255,m[w+2]=h*r/255,m[w+3]=l*s/255;break;case"mask":m[w+3]=s}},getUniformLocations:function(t,e){return{uTransformMatrix:t.getUniformLocation(e,"uTransformMatrix"),uImage:t.getUniformLocation(e,"uImage")}},sendUniformData:function(t,e){var i=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,i)},toObject:function(){return{type:this.type,image:this.image&&this.image.toObject(),mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendImage.fromObject=function(t,i){e.Image.fromObject(t.image,function(n){var r=e.util.object.clone(t);r.image=n,i(new e.Image.filters.BlendImage(r))})}}(e),function(t){var e=t.fabric||(t.fabric={}),i=Math.pow,n=Math.floor,r=Math.sqrt,s=Math.abs,o=Math.round,a=Math.sin,h=Math.ceil,l=e.Image.filters,c=e.util.createClass;l.Resize=c(l.BaseFilter,{type:"Resize",resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3,getUniformLocations:function(t,e){return{uDelta:t.getUniformLocation(e,"uDelta"),uTaps:t.getUniformLocation(e,"uTaps")}},sendUniformData:function(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)},retrieveShader:function(t){var e=this.getFilterWindow(),i=this.type+"_"+e;if(!t.programCache.hasOwnProperty(i)){var n=this.generateShader(e);t.programCache[i]=this.createProgram(t.context,n)}return t.programCache[i]},getFilterWindow:function(){var t=this.tempScale;return Math.ceil(this.lanczosLobes/t)},getTaps:function(){for(var t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,i=this.getFilterWindow(),n=new Array(i),r=1;r<=i;r++)n[r-1]=t(r*e);return n},generateShader:function(t){for(var e=new Array(t),i=this.fragmentSourceTOP,n=1;n<=t;n++)e[n-1]=n+".0 * uDelta";return i+="uniform float uTaps["+t+"];\n",i+="void main() {\n",i+=" vec4 color = texture2D(uTexture, vTexCoord);\n",i+=" float sum = 1.0;\n",e.forEach(function(t,e){i+=" color += texture2D(uTexture, vTexCoord + "+t+") * uTaps["+e+"];\n",i+=" color += texture2D(uTexture, vTexCoord - "+t+") * uTaps["+e+"];\n",i+=" sum += 2.0 * uTaps["+e+"];\n"}),i+=" gl_FragColor = color / sum;\n",i+="}"},fragmentSourceTOP:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\n",applyTo:function(t){t.webgl?(t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t),t.sourceHeight=t.destinationHeight):this.applyTo2d(t)},isNeutralState:function(){return 1===this.scaleX&&1===this.scaleY},lanczosCreate:function(t){return function(e){if(e>=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(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,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=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")),((a=m.sliceByTwo).width<1.5*i||a.height<r)&&(a.width=1.5*i,a.height=r),(h=a.getContext("2d")).clearRect(0,0,1.5*i,r),h.putImageData(l,0,0),s=n(s),o=n(o);!u||!d;)i=f,r=g,s<n(f*c)?f=n(f*c):(f=s,u=!0),o<n(g*c)?g=n(g*c):(g=o,d=!0),h.drawImage(a,p,_,i,r,v,y,f,g),p=v,_=y,y+=g;return h.getImageData(p,_,s,o)},lanczosResize:function(t,e,o,a,l){var c=t.imageData.data,u=t.ctx.createImageData(a,l),d=u.data,f=this.lanczosCreate(this.lanczosLobes),g=this.rcpScaleX,m=this.rcpScaleY,p=2/this.rcpScaleX,_=2/this.rcpScaleY,v=h(g*this.lanczosLobes/2),y=h(m*this.lanczosLobes/2),w={},C={},E={};return function t(h){var S,b,T,I,x,O,R,A,D,L,M;for(C.x=(h+.5)*g,E.x=n(C.x),S=0;S<l;S++){for(C.y=(S+.5)*m,E.y=n(C.y),x=0,O=0,R=0,A=0,D=0,b=E.x-v;b<=E.x+v;b++)if(!(b<0||b>=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>=o||(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)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h<a?t(h):u}(0)},bilinearFiltering:function(t,e,i,r,s){var o,a,h,l,c,u,d,f,g,m=0,p=this.rcpScaleX,_=this.rcpScaleY,v=4*(e-1),y=t.imageData.data,w=t.ctx.createImageData(r,s),C=w.data;for(h=0;h<s;h++)for(l=0;l<r;l++)for(c=p*l-(o=n(p*l)),u=_*h-(a=n(_*h)),g=4*(a*e+o),d=0;d<4;d++)f=y[g+d]*(1-c)*(1-u)+y[g+4+d]*c*(1-u)+y[g+v+d]*u*(1-c)+y[g+v+4+d]*c*u,C[m++]=f;return w},hermiteFastResize:function(t,e,i,o,a){for(var l=this.rcpScaleX,c=this.rcpScaleY,u=h(l/2),d=h(c/2),f=t.imageData.data,g=t.ctx.createImageData(o,a),m=g.data,p=0;p<a;p++)for(var _=0;_<o;_++){for(var v=4*(_+p*o),y=0,w=0,C=0,E=0,S=0,b=0,T=0,I=(p+.5)*c,x=n(p*c);x<(p+1)*c;x++)for(var O=s(I-(x+.5))/d,R=(_+.5)*l,A=O*O,D=n(_*l);D<(_+1)*l;D++){var L=s(R-(D+.5))/u,M=r(A+L*L);M>1&&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;e<n;e+=4)i[e]=s*(i[e]-128)+128,i[e+1]=s*(i[e+1]-128)+128,i[e+2]=s*(i[e+2]-128)+128}},getUniformLocations:function(t,e){return{uContrast:t.getUniformLocation(e,"uContrast")}},sendUniformData:function(t,e){t.uniform1f(e.uContrast,this.contrast)}}),e.Image.filters.Contrast.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Saturation=n(i.BaseFilter,{type:"Saturation",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uSaturation;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat rgMax = max(color.r, color.g);\nfloat rgbMax = max(rgMax, color.b);\ncolor.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\ncolor.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\ncolor.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\ngl_FragColor = color;\n}",saturation:0,mainParameter:"saturation",applyTo2d:function(t){if(0!==this.saturation){var e,i,n=t.imageData.data,r=n.length,s=-this.saturation;for(e=0;e<r;e+=4)i=Math.max(n[e],n[e+1],n[e+2]),n[e]+=i!==n[e]?(i-n[e])*s:0,n[e+1]+=i!==n[e+1]?(i-n[e+1])*s:0,n[e+2]+=i!==n[e+2]?(i-n[e+2])*s:0}},getUniformLocations:function(t,e){return{uSaturation:t.getUniformLocation(e,"uSaturation")}},sendUniformData:function(t,e){t.uniform1f(e.uSaturation,-this.saturation)}}),e.Image.filters.Saturation.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Vibrance=n(i.BaseFilter,{type:"Vibrance",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uVibrance;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat max = max(color.r, max(color.g, color.b));\nfloat avg = (color.r + color.g + color.b) / 3.0;\nfloat amt = (abs(max - avg) * 2.0) * uVibrance;\ncolor.r += max != color.r ? (max - color.r) * amt : 0.00;\ncolor.g += max != color.g ? (max - color.g) * amt : 0.00;\ncolor.b += max != color.b ? (max - color.b) * amt : 0.00;\ngl_FragColor = color;\n}",vibrance:0,mainParameter:"vibrance",applyTo2d:function(t){if(0!==this.vibrance){var e,i,n,r,s=t.imageData.data,o=s.length,a=-this.vibrance;for(e=0;e<o;e+=4)i=Math.max(s[e],s[e+1],s[e+2]),n=(s[e]+s[e+1]+s[e+2])/3,r=2*Math.abs(i-n)/255*a,s[e]+=i!==s[e]?(i-s[e])*r:0,s[e+1]+=i!==s[e+1]?(i-s[e+1])*r:0,s[e+2]+=i!==s[e+2]?(i-s[e+2])*r:0}},getUniformLocations:function(t,e){return{uVibrance:t.getUniformLocation(e,"uVibrance")}},sendUniformData:function(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}}),e.Image.filters.Vibrance.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Blur=n(i.BaseFilter,{type:"Blur",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\nconst float nSamples = 15.0;\nvec3 v3offset = vec3(12.9898, 78.233, 151.7182);\nfloat random(vec3 scale) {\nreturn fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n}\nvoid main() {\nvec4 color = vec4(0.0);\nfloat total = 0.0;\nfloat offset = random(v3offset);\nfor (float t = -nSamples; t <= nSamples; t++) {\nfloat percent = (t + offset - 0.5) / nSamples;\nfloat weight = 1.0 - abs(percent);\ncolor += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\ntotal += weight;\n}\ngl_FragColor = color / total;\n}",blur:0,mainParameter:"blur",applyTo:function(t){t.webgl?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},applyTo2d:function(t){t.imageData=this.simpleBlur(t)},simpleBlur:function(t){var i,n,r=t.filterBackend.resources,s=t.imageData.width,o=t.imageData.height;r.blurLayer1||(r.blurLayer1=e.util.createCanvasElement(),r.blurLayer2=e.util.createCanvasElement()),i=r.blurLayer1,n=r.blurLayer2,i.width===s&&i.height===o||(n.width=i.width=s,n.height=i.height=o);var a,h,l,c,u=i.getContext("2d"),d=n.getContext("2d"),f=.06*this.blur*.5;for(u.putImageData(t.imageData,0,0),d.clearRect(0,0,s,o),c=-15;c<=15;c++)l=f*(h=c/15)*s+(a=(Math.random()-.5)/4),d.globalAlpha=1-Math.abs(h),d.drawImage(i,l,a),u.drawImage(n,0,0),d.globalAlpha=1,d.clearRect(0,0,n.width,n.height);for(c=-15;c<=15;c++)l=f*(h=c/15)*o+(a=(Math.random()-.5)/4),d.globalAlpha=1-Math.abs(h),d.drawImage(i,a,l),u.drawImage(n,0,0),d.globalAlpha=1,d.clearRect(0,0,n.width,n.height);t.ctx.drawImage(i,0,0);var g=t.ctx.getImageData(0,0,i.width,i.height);return u.globalAlpha=1,u.clearRect(0,0,i.width,i.height),g},getUniformLocations:function(t,e){return{delta:t.getUniformLocation(e,"uDelta")}},sendUniformData:function(t,e){var i=this.chooseRightDelta();t.uniform2fv(e.delta,i)},chooseRightDelta:function(){var t,e=1,i=[0,0];return this.horizontal?this.aspectRatio>1&&(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],o=1/n[1],a=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<r;e++)this.rVals[e]=255*Math.pow(e/255,s),this.gVals[e]=255*Math.pow(e/255,o),this.bVals[e]=255*Math.pow(e/255,a);for(e=0,r=i.length;e<r;e+=4)i[e]=this.rVals[i[e]],i[e+1]=this.gVals[i[e+1]],i[e+2]=this.bVals[i[e+2]]},getUniformLocations:function(t,e){return{uGamma:t.getUniformLocation(e,"uGamma")}},sendUniformData:function(t,e){t.uniform3fv(e.uGamma,this.gamma)}}),e.Image.filters.Gamma.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Composed=n(i.BaseFilter,{type:"Composed",subFilters:[],initialize:function(t){this.callSuper("initialize",t),this.subFilters=this.subFilters.slice(0)},applyTo:function(t){t.passes+=this.subFilters.length-1,this.subFilters.forEach(function(e){e.applyTo(t)})},toObject:function(){return e.util.object.extend(this.callSuper("toObject"),{subFilters:this.subFilters.map(function(t){return t.toObject()})})},isNeutralState:function(){return!this.subFilters.some(function(t){return!t.isNeutralState()})}}),e.Image.filters.Composed.fromObject=function(t,i){var n=(t.subFilters||[]).map(function(t){return new e.Image.filters[t.type](t)}),r=new e.Image.filters.Composed({subFilters:n});return i&&i(r),r}}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.HueRotation=n(i.ColorMatrix,{type:"HueRotation",rotation:0,mainParameter:"rotation",calculateMatrix:function(){var t=this.rotation*Math.PI,i=e.util.cos(t),n=e.util.sin(t),r=1/3,s=Math.sqrt(r)*n,o=1-i;this.matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],this.matrix[0]=i+o/3,this.matrix[1]=r*o-s,this.matrix[2]=r*o+s,this.matrix[5]=r*o+s,this.matrix[6]=i+r*o,this.matrix[7]=r*o-s,this.matrix[10]=r*o-s,this.matrix[11]=r*o+s,this.matrix[12]=i+r*o},isNeutralState:function(t){return this.calculateMatrix(),i.BaseFilter.prototype.isNeutralState.call(this,t)},applyTo:function(t){this.calculateMatrix(),i.BaseFilter.prototype.applyTo.call(this,t)}}),e.Image.filters.HueRotation.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.clone;if(e.Text)e.warn("fabric.Text is already defined");else{var n="fontFamily fontWeight fontSize text underline overline linethrough textAlign fontStyle lineHeight textBackgroundColor charSpacing styles direction path pathStartOffset pathSide pathAlign".split(" ");e.Text=e.util.createClass(e.Object,{_dimensionAffectingProps:["fontSize","fontWeight","fontFamily","fontStyle","lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],_reNewline:/\r?\n/,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,type:"text",fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:"left",fontStyle:"normal",lineHeight:1.16,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},textBackgroundColor:"",stateProperties:e.Object.prototype.stateProperties.concat(n),cacheProperties:e.Object.prototype.cacheProperties.concat(n),stroke:null,shadow:null,path:null,pathStartOffset:0,pathSide:"left",pathAlign:"baseline",_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,styles:null,_measuringContext:null,deltaY:0,direction:"ltr",_styleProperties:["stroke","strokeWidth","fill","fontFamily","fontSize","fontWeight","fontStyle","underline","overline","linethrough","deltaY","textBackgroundColor"],__charBounds:[],CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,initialize:function(t,e){this.styles=e&&e.styles||{},this.text=t,this.__skipDimension=!0,this.callSuper("initialize",e),this.path&&this.setPathInfo(),this.__skipDimension=!1,this.initDimensions(),this.setCoords(),this.setupState({propertySet:"_dimensionAffectingProps"})},setPathInfo:function(){var t=this.path;t&&(t.segmentsInfo=e.util.getPathSegmentsInfo(t.path))},getMeasuringContext:function(){return e._measuringContext||(e._measuringContext=this.canvas&&this.canvas.contextCache||e.util.createCanvasElement().getContext("2d")),e._measuringContext},_splitText:function(){var t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t},initDimensions:function(){this.__skipDimension||(this._splitText(),this._clearCache(),this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.saveState({propertySet:"_dimensionAffectingProps"}))},enlargeSpaces:function(){for(var t,e,i,n,r,s,o,a=0,h=this._textLines.length;a<h;a++)if(("justify"===this.textAlign||a!==h-1&&!this.isEndOfWrapping(a))&&(n=0,r=this._textLines[a],(e=this.getLineWidth(a))<this.width&&(o=this.textLines[a].match(this._reSpacesAndTabs)))){i=o.length,t=(this.width-e)/i;for(var l=0,c=r.length;l<=c;l++)s=this.__charBounds[a][l],this._reSpaceAndTab.test(r[l])?(s.width+=t,s.kernedWidth+=t,s.left+=n,n+=t):s.left+=n}},isEndOfWrapping:function(t){return t===this._textLines.length-1},missingNewlineOffset:function(){return 1},toString:function(){return"#<fabric.Text ("+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'" }>'},_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;e<i;e++){var n=this.getLineWidth(e);n>t&&(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,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g<m;g++)if(e=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){n=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,r=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,_=n.length;p<_;p++)s=this.__charBounds[g][p],o=this.getValueOfPropertyAt(g,p,"textBackgroundColor"),f?(t.save(),t.translate(s.renderLeft,s.renderTop),t.rotate(s.angle),t.fillStyle=o,o&&t.fillRect(-s.width/2,-e/this.lineHeight*(1-this._fontSizeFraction),s.width,e/this.lineHeight),t.restore()):o!==r?(a=l+i+u,"rtl"===this.direction&&(a=this.width-a-d),t.fillStyle=r,r&&t.fillRect(a,c,d,e/this.lineHeight),u=s.left,d=s.width,r=o):d+=s.kernedWidth;o&&!f&&(a=l+i+u,"rtl"===this.direction&&(a=this.width-a-d),t.fillStyle=o,t.fillRect(a,c,d,e/this.lineHeight)),c+=e}else c+=e;t.fillStyle=h,this._removeShadow(t)}},getFontCache:function(t){var i=t.fontFamily.toLowerCase();e.charWidthsCache[i]||(e.charWidthsCache[i]={});var n=e.charWidthsCache[i],r=t.fontStyle.toLowerCase()+"_"+(t.fontWeight+"").toLowerCase();return n[r]||(n[r]={}),n[r]},_measureChar:function(t,e,i,n){var r,s,o,a,h=this.getFontCache(e),l=i+t,c=this._getFontDeclaration(e)===this._getFontDeclaration(n),u=e.fontSize/this.CACHE_FONT_SIZE;if(i&&void 0!==h[i]&&(o=h[i]),void 0!==h[t]&&(a=r=h[t]),c&&void 0!==h[l]&&(a=(s=h[l])-o),void 0===r||void 0===o||void 0===s){var d=this.getMeasuringContext();this._setTextStyles(d,e,!0)}return void 0===r&&(a=r=d.measureText(t).width,h[t]=r),void 0===o&&c&&i&&(o=d.measureText(i).width,h[i]=o),c&&void 0===s&&(s=d.measureText(l).width,h[l]=s,a=s-o),{width:r*u,kernedWidth:a*u}},getHeightOfChar:function(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")},measureLine:function(t){var e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e},_measureLine:function(t){var i,n,r,s,o,a,h=0,l=this._textLines[t],c=new Array(l.length),u=0,d=this.path,f="right"===this.pathSide;for(this.__charBounds[t]=c,i=0;i<l.length;i++)n=l[i],s=this._getGraphemeBox(n,t,i,r),c[i]=s,h+=s.kernedWidth,r=n;if(c[i]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize},d){switch(a=d.segmentsInfo[d.segmentsInfo.length-1].length,(o=e.util.getPointOnPath(d.path,0,d.segmentsInfo)).x+=d.pathOffset.x,o.y+=d.pathOffset.y,this.textAlign){case"left":u=f?a-h:0;break;case"center":u=(a-h)/2;break;case"right":u=f?0:a-h}for(u+=this.pathStartOffset*(f?-1:1),i=f?l.length-1:0;f?i>=0:i<l.length;f?i--:i++)s=c[i],u>a?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.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;n<r;n++)i=Math.max(this.getHeightOfChar(t,n),i);return this.__lineHeights[t]=i*this.lineHeight*this._fontSizeMult},calcTextHeight:function(){for(var t,e=0,i=0,n=this._textLines.length;i<n;i++)t=this.getHeightOfLine(i),e+=i===n-1?t/this.lineHeight:t;return e},_getLeftOffset:function(){return"ltr"===this.direction?-this.width/2:this.width/2},_getTopOffset:function(){return-this.height/2},_renderTextCommon:function(t,e){t.save();for(var i=0,n=this._getLeftOffset(),r=this._getTopOffset(),s=0,o=this._textLines.length;s<o;s++){var a=this.getHeightOfLine(s),h=a/this.lineHeight,l=this._getLineLeftOffset(s);this._renderTextLine(e,t,this._textLines[s],n+l,r+i+h,s),i+=a}t.restore()},_renderTextFill:function(t){(this.fill||this.styleHas("fill"))&&this._renderTextCommon(t,"fillText")},_renderTextStroke:function(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())},_renderChars:function(t,e,i,n,r,s){var o,a,h,l,c,u=this.getHeightOfLine(s),d=-1!==this.textAlign.indexOf("justify"),f="",g=0,m=this.path,p=!d&&0===this.charSpacing&&this.isEmptyStyles(s)&&!m,_="ltr"===this.direction,v="ltr"===this.direction?1:-1,y=e.canvas.getAttribute("dir");if(e.save(),y!==this.direction&&(e.canvas.setAttribute("dir",_?"ltr":"rtl"),e.direction=_?"ltr":"rtl",e.textAlign=_?"left":"right"),r-=u*this._fontSizeFraction/this.lineHeight,p)return this._renderChar(t,e,s,0,i.join(""),n,r,u),void e.restore();for(var w=0,C=i.length-1;w<=C;w++)l=w===C||this.charSpacing||m,f+=i[w],h=this.__charBounds[s][w],0===g?(n+=v*(h.kernedWidth-h.width),g+=h.width):g+=h.kernedWidth,d&&!l&&this._reSpaceAndTab.test(i[w])&&(l=!0),l||(o=o||this.getCompleteStyleDeclaration(s,w),a=this.getCompleteStyleDeclaration(s,w+1),l=this._hasStyleChanged(o,a)),l&&(m?(e.save(),e.translate(h.renderLeft,h.renderTop),e.rotate(h.angle),this._renderChar(t,e,s,w,f,-g/2,0,u),e.restore()):(c=n,this._renderChar(t,e,s,w,f,c,r,u)),f="",o=a,n+=v*g,g=0);e.restore()},_applyPatternGradientTransformText:function(t){var i,n=e.util.createCanvasElement(),r=this.width+this.strokeWidth,s=this.height+this.strokeWidth;return n.width=r,n.height=s,(i=n.getContext("2d")).beginPath(),i.moveTo(0,0),i.lineTo(r,0),i.lineTo(r,s),i.lineTo(0,s),i.closePath(),i.translate(r/2,s/2),i.fillStyle=t.toLive(i),this._applyPatternGradientTransform(i,t),i.fill(),i.createPattern(n,"no-repeat")},handleFiller:function(t,e,i){var n,r;return i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?(n=-this.width/2,r=-this.height/2,t.translate(n,r),t[e]=this._applyPatternGradientTransformText(i),{offsetX:n,offsetY:r}):(t[e]=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):(t[e]=i,{offsetX:0,offsetY:0})},_setStrokeStyles:function(t,e){return t.lineWidth=e.strokeWidth,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",e.stroke)},_setFillStyles:function(t,e){return this.handleFiller(t,"fillStyle",e.fill)},_renderChar:function(t,e,i,n,r,s,o){var a,h,l=this._getStyleDeclaration(i,n),c=this.getCompleteStyleDeclaration(i,n),u="fillText"===t&&c.fill,d="strokeText"===t&&c.stroke&&c.strokeWidth;(d||u)&&(e.save(),u&&(a=this._setFillStyles(e,c)),d&&(h=this._setStrokeStyles(e,c)),e.font=this._getFontDeclaration(c),l&&l.textBackgroundColor&&this._removeShadow(e),l&&l.deltaY&&(o+=l.deltaY),u&&e.fillText(r,s-a.offsetX,o-a.offsetY),d&&e.strokeText(r,s-h.offsetX,o-h.offsetY),e.restore())},setSuperscript:function(t,e){return this._setScript(t,e,this.superscript)},setSubscript:function(t,e){return this._setScript(t,e,this.subscript)},_setScript:function(t,e,i){var n=this.get2DCursorLocation(t,!0),r=this.getValueOfPropertyAt(n.lineIndex,n.charIndex,"fontSize"),s=this.getValueOfPropertyAt(n.lineIndex,n.charIndex,"deltaY"),o={fontSize:r*i.size,deltaY:s+r*i.baseline};return this.setSelectionStyles(o,t,e),this},_hasStyleChanged:function(t,e){return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.deltaY!==e.deltaY},_hasStyleChangedForSvg:function(t,e){return this._hasStyleChanged(t,e)||t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough},_getLineLeftOffset:function(t){var e=this.getLineWidth(t),i=this.width-e,n=this.textAlign,r=this.direction,s=0,o=this.isEndOfWrapping(t);return"justify"===n||"justify-center"===n&&!o||"justify-right"===n&&!o||"justify-left"===n&&!o?0:("center"===n&&(s=i/2),"right"===n&&(s=i),"justify-center"===n&&(s=i/2),"justify-right"===n&&(s=i),"rtl"===r&&(s-=i),s)},_clearCache:function(){this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]},_shouldClearDimensionCache:function(){var t=this._forceClearCache;return t||(t=this.hasStateChanged("_dimensionAffectingProps")),t&&(this.dirty=!0,this._forceClearCache=!1),t},getLineWidth:function(t){if(void 0!==this.__lineWidths[t])return this.__lineWidths[t];var e=this.measureLine(t).width;return this.__lineWidths[t]=e,e},_getWidthOfCharSpacing:function(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0},getValueOfPropertyAt:function(t,e,i){var n=this._getStyleDeclaration(t,e);return n&&void 0!==n[i]?n[i]:this[i]},_renderTextDecoration:function(t,e){if(this[e]||this.styleHas(e)){for(var i,n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v=this._getLeftOffset(),y=this._getTopOffset(),w=this.path,C=this._getWidthOfCharSpacing(),E=this.offsets[e],S=0,b=this._textLines.length;S<b;S++)if(i=this.getHeightOfLine(S),this[e]||this.styleHas(e,S)){h=this._textLines[S],m=i/this.lineHeight,s=this._getLineLeftOffset(S),u=0,d=0,l=this.getValueOfPropertyAt(S,0,e),_=this.getValueOfPropertyAt(S,0,"fill"),c=y+m*(1-this._fontSizeFraction),n=this.getHeightOfChar(S,0),o=this.getValueOfPropertyAt(S,0,"deltaY");for(var T=0,I=h.length;T<I;T++)if(f=this.__charBounds[S][T],g=this.getValueOfPropertyAt(S,T,e),p=this.getValueOfPropertyAt(S,T,"fill"),r=this.getHeightOfChar(S,T),a=this.getValueOfPropertyAt(S,T,"deltaY"),w&&g&&p)t.save(),t.fillStyle=_,t.translate(f.renderLeft,f.renderTop),t.rotate(f.angle),t.fillRect(-f.kernedWidth/2,E*r+a,f.kernedWidth,this.fontSize/15),t.restore();else if((g!==l||p!==_||r!==n||a!==o)&&d>0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}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+E*n+o,d-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,o=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",o].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=[],o=0;o<i.length;o++)n[o]=e.util.string.graphemeSplit(i[o]),s=s.concat(n[o],r);return s.pop(),{_unwrappedLines:n,lines:i,graphemeText:s,graphemeLines:n}},toObject:function(t){var e=n.concat(t),r=this.callSuper("toObject",e);return r.styles=i(this.styles,!0),r.path&&(r.path=this.path.toObject()),r},set:function(t,e){this.callSuper("set",t,e);var i=!1,n=!1;if("object"==typeof t)for(var r in t)"path"===r&&this.setPathInfo(),i=i||-1!==this._dimensionAffectingProps.indexOf(r),n=n||"path"===r;else i=-1!==this._dimensionAffectingProps.indexOf(t),n="path"===t;return n&&this.setPathInfo(),i&&(this.initDimensions(),this.setCoords()),this},complexity:function(){return 1}}),e.Text.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size letter-spacing text-decoration text-anchor".split(" ")),e.Text.DEFAULT_SVG_FONT_SIZE=16,e.Text.fromElement=function(t,n,r){if(!t)return n(null);var s=e.parseAttributes(t,e.Text.ATTRIBUTE_NAMES),o=s.textAnchor||"left";if((r=e.util.object.extend(r?i(r):{},s)).top=r.top||0,r.left=r.left||0,s.textDecoration){var a=s.textDecoration;-1!==a.indexOf("underline")&&(r.underline=!0),-1!==a.indexOf("overline")&&(r.overline=!0),-1!==a.indexOf("line-through")&&(r.linethrough=!0),delete r.textDecoration}"dx"in s&&(r.left+=s.dx),"dy"in s&&(r.top+=s.dy),"fontSize"in r||(r.fontSize=e.Text.DEFAULT_SVG_FONT_SIZE);var h="";"textContent"in t?h=t.textContent:"firstChild"in t&&null!==t.firstChild&&"data"in t.firstChild&&null!==t.firstChild.data&&(h=t.firstChild.data),h=h.replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," ");var l=r.strokeWidth;r.strokeWidth=0;var c=new e.Text(h,r),u=c.getScaledHeight()/c.height,d=((c.height+c.strokeWidth)*c.lineHeight-c.height)*u,f=c.getScaledHeight()+d,g=0;"center"===o&&(g=c.getScaledWidth()/2),"right"===o&&(g=c.getScaledWidth()),c.set({left:c.left-g,top:c.top-(f-c.fontSize*(.07+c._fontSizeFraction))/c.lineHeight,strokeWidth:void 0!==l?l:1}),n(c)},e.Text.fromObject=function(t,n){var r=i(t),s=t.path;return delete r.path,e.Object._fromObject("Text",r,function(t){s?e.Object._fromObject("Path",s,function(e){t.set("path",e),n(t)},"path"):n(t)},"text")},e.Text.genericFonts=["sans-serif","serif","cursive","fantasy","monospace"],e.util.createAccessors&&e.util.createAccessors(e.Text)}}(e),b.util.object.extend(b.Text.prototype,{isEmptyStyles:function(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;var e=void 0===t?this.styles:{line:this.styles[t]};for(var i in e)for(var n in e[i])for(var r in e[i][n])return!1;return!0},styleHas:function(t,e){if(!this.styles||!t||""===t)return!1;if(void 0!==e&&!this.styles[e])return!1;var i=void 0===e?this.styles:{0:this.styles[e]};for(var n in i)for(var r in i[n])if(void 0!==i[n][r][t])return!0;return!1},cleanStyle:function(t){if(!this.styles||!t||""===t)return!1;var e,i,n=this.styles,r=0,s=!0,o=0;for(var a in n){for(var h in e=0,n[a]){var l;r++,(l=n[a][h]).hasOwnProperty(t)?(i?l[t]!==i&&(s=!1):i=l[t],l[t]===this[t]&&delete l[t]):s=!1,0!==Object.keys(l).length?e++:delete n[a][h]}0===e&&delete n[a]}for(var c=0;c<this._textLines.length;c++)o+=this._textLines[c].length;s&&r===o&&(this[t]=i,this.removeStyle(t))},removeStyle:function(t){if(this.styles&&t&&""!==t){var e,i,n,r=this.styles;for(i in r){for(n in e=r[i])delete e[n][t],0===Object.keys(e[n]).length&&delete e[n];0===Object.keys(e).length&&delete r[i]}}},_extendStyles:function(t,e){var i=this.get2DCursorLocation(t);this._getLineStyle(i.lineIndex)||this._setLineStyle(i.lineIndex),this._getStyleDeclaration(i.lineIndex,i.charIndex)||this._setStyleDeclaration(i.lineIndex,i.charIndex,{}),b.util.object.extend(this._getStyleDeclaration(i.lineIndex,i.charIndex),e)},get2DCursorLocation:function(t,e){void 0===t&&(t=this.selectionStart);for(var i=e?this._unwrappedTextLines:this._textLines,n=i.length,r=0;r<n;r++){if(t<=i[r].length)return{lineIndex:r,charIndex:t};t-=i[r].length+this.missingNewlineOffset(r)}return{lineIndex:r-1,charIndex:i[r-1].length<t?i[r-1].length:t}},getSelectionStyles:function(t,e,i){void 0===t&&(t=this.selectionStart||0),void 0===e&&(e=this.selectionEnd||t);for(var n=[],r=t;r<e;r++)n.push(this.getStyleAtPosition(r,i));return n},getStyleAtPosition:function(t,e){var i=this.get2DCursorLocation(t);return(e?this.getCompleteStyleDeclaration(i.lineIndex,i.charIndex):this._getStyleDeclaration(i.lineIndex,i.charIndex))||{}},setSelectionStyles:function(t,e,i){void 0===e&&(e=this.selectionStart||0),void 0===i&&(i=this.selectionEnd||e);for(var n=e;n<i;n++)this._extendStyles(n,t);return this._forceClearCache=!0,this},_getStyleDeclaration:function(t,e){var i=this.styles&&this.styles[t];return i?i[e]:null},getCompleteStyleDeclaration:function(t,e){for(var i,n=this._getStyleDeclaration(t,e)||{},r={},s=0;s<this._styleProperties.length;s++)r[i=this._styleProperties[s]]=void 0===n[i]?this[i]:n[i];return r},_setStyleDeclaration:function(t,e,i){this.styles[t][e]=i},_deleteStyleDeclaration:function(t,e){delete this.styles[t][e]},_getLineStyle:function(t){return!!this.styles[t]},_setLineStyle:function(t){this.styles[t]={}},_deleteLineStyle:function(t){delete this.styles[t]}}),function(){function t(t){t.textDecoration&&(t.textDecoration.indexOf("underline")>-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,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h<i;h++)s+=this.getHeightOfLine(h);e=this._getLineLeftOffset(i);var l=this.__charBounds[i][n];return l&&(o=l.left),0!==this.charSpacing&&n===this._textLines[i].length&&(o-=this._getWidthOfCharSpacing()),r={top:s,left:e+(o>0?o: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"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(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-a/2,h+t.top+l,a,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),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u<h)p=r&&!this.isEndOfWrapping(u)?this.width:this.getLineWidth(u)||5;else if(u===h)if(0===c)p=this.__charBounds[h][c].left;else{var _=this._getWidthOfCharSpacing();p=this.__charBounds[h][c-1].left+this.__charBounds[h][c-1].width-_}d=g,(this.lineHeight<1||u===h&&this.lineHeight>1)&&(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+=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}}}),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<this._text.length;)e++,i++;return t+e},findLineBoundaryLeft:function(t){for(var e=0,i=t-1;!/\n/.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])&&i<this._text.length;)e++,i++;return t+e},searchWordBoundary:function(t,e){for(var i=this._text,n=this._reSpace.test(i[t])?t-1:t,r=i[n],s=b.reNonWord;!s.test(r)&&n>0&&n<i.length;)r=i[n+=e];return s.test(r)&&(n+=1===e?0:1),n},selectWord:function(t){t=t||this.selectionStart;var e=this.searchWordBoundary(t,-1),i=this.searchWordBoundary(t,1);this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()},selectLine:function(t){t=t||this.selectionStart;var e=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);return this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this},enterEditing:function(t){if(!this.isEditing&&this.editable)return this.canvas&&(this.canvas.calcOffset(),this.exitEditingOnOthers(this.canvas)),this.isEditing=!0,this.initHiddenTextarea(t),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick(),this.fire("editing:entered"),this._fireSelectionChanged(),this.canvas?(this.canvas.fire("text:editing:entered",{target:this}),this.initMouseMoveHandler(),this.canvas.requestRenderAll(),this):this},exitEditingOnOthers:function(t){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.selected=!1,t.isEditing&&t.exitEditing()})},initMouseMoveHandler:function(){this.canvas.on("mouse:move",this.mouseMoveHandler)},mouseMoveHandler:function(t){if(this.__isMousedown&&this.isEditing){var e=this.getSelectionStartFromPointer(t.e),i=this.selectionStart,n=this.selectionEnd;(e===this.__selectionStartOnMouseDown&&i!==n||i!==e&&n!==e)&&(e>this.__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,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.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),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i<this._unwrappedTextLines[o].length;i++)delete this.styles[o][i];if(this.styles[h])for(i=l;i<this._unwrappedTextLines[h].length;i++)(n=this.styles[h][i])&&(this.styles[o]||(this.styles[o]={}),this.styles[o][a+i-l]=n);for(i=o+1;i<=h;i++)delete this.styles[i];this.shiftLineStyles(h,o-h)}else if(this.styles[o]){n=this.styles[o];var c,u,d=l-a;for(i=a;i<l;i++)delete n[i];for(u in this.styles[o])(c=parseInt(u,10))>=l&&(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={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(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 o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}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 h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o<t.length;o++)"\n"===t[o]?r[++s]=0:r[s]++;for(r[0]>0&&(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),o=1;o<s;o++)r[o]>0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],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&&i<e?"right"===this._selectionDirection?this.selectionEnd=i:this.selectionStart=i:(e===t?this._selectionDirection="right":"left"===this._selectionDirection&&(this._selectionDirection="right",this.selectionStart=e),this.selectionEnd=i)},setSelectionInBoundaries:function(){var t=this.text.length;this.selectionStart>t?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,o=0,a=0,h=0,l=this._textLines.length;h<l&&s<=i.y;h++)s+=this.getHeightOfLine(h)*this.scaleY,a=h,h>0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;c<u&&(n=r,(r+=this.__charBounds[a][c].kernedWidth*this.scaleX)<=i.x);c++)o++;return this._getNewSelectionStartFromOffset(i,n,r,o,u)},_getNewSelectionStartFromOffset:function(t,e,i,n,r){var s=t.x-e,o=i-t.x,a=n+(o>s||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),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,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,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):l<h&&(i=m?this._text.slice(d+c,d):this._text.slice(u,u-c)),n=a.slice(g.selectionEnd-c,g.selectionEnd),i&&i.length&&(n.length&&(r=this.getSelectionStyles(u,u+1,!1),r=n.map(function(){return r[0]})),f?(s=u,o=d):m?(s=d-i.length,o=d):(s=d,o=d+i.length),this.removeStyleFromTo(s,o)),n.length&&(e&&n.join("")===b.copiedText&&!b.disableStyleCopyPaste&&(r=b.copiedTextStyle),this.insertNewStyleBlock(n,u,r)),this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())}},onCompositionStart:function(){this.inCompositionMode=!0},onCompositionEnd:function(){this.inCompositionMode=!1},onCompositionUpdate:function(t){this.compositionStart=t.target.selectionStart,this.compositionEnd=t.target.selectionEnd,this.updateTextareaPosition()},copy:function(){this.selectionStart!==this.selectionEnd&&(b.copiedText=this.getSelectedText(),b.disableStyleCopyPaste?b.copiedTextStyle=null:b.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0)},paste:function(){this.fromPaste=!0},_getClipboardData:function(t){return t&&t.clipboardData||b.window.clipboardData},_getWidthBeforeCursor:function(t,e){var i,n=this._getLineLeftOffset(t);return e>0&&(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,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+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,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;a<h;a++)if((s+=i=this.__charBounds[t][a].width)>e){n=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)<u?a:a-1;break}return n||(o=r.length-1),o},moveCursorDown:function(t){this.selectionStart>=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<text xml:space="preserve" ',this.fontFamily?'font-family="'+this.fontFamily.replace(/"/g,"'")+'" ':"",this.fontSize?'font-size="'+this.fontSize+'" ':"",this.fontStyle?'font-style="'+this.fontStyle+'" ':"",this.fontWeight?'font-weight="'+this.fontWeight+'" ':"",e?'text-decoration="'+e+'" ':"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",t.textSpans.join(""),"</text>\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o<a;o++)i=this._getLineLeftOffset(o),(this.textBackgroundColor||this.styleHas("textBackgroundColor",o))&&this._setSVGTextLineBg(r,o,e+i,s),this._setSVGTextLineText(n,o,e+i,s),s+=this.getHeightOfLine(o);return{textSpans:n,textBgRects:r}},_createTextCharSpan:function(i,n,r,s){var o=i!==i.trim()||i.match(e),a=this.getSvgSpanStyles(n,o),h=a?'style="'+a+'"':"",l=n.deltaY,c="",u=b.Object.NUM_FRACTION_DIGITS;return l&&(c=' dy="'+t(l,u)+'" '),['<tspan x="',t(r,u),'" y="',t(s,u),'" ',c,h,">",b.util.string.escapeXml(i),"</tspan>"].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t<rect ",this._getFillAttributes(i),' x="',t(n,a),'" y="',t(r,a),'" width="',t(s,a),'" height="',t(o,a),'"></rect>\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;u<d;u++)r=this.__charBounds[e][u],(s=this.getValueOfPropertyAt(e,u,"textBackgroundColor"))!==c?(c&&this._pushTextBgRect(t,c,i+l,n,h,a),l=r.left,h=r.width,c=s):h+=r.kernedWidth;s&&this._pushTextBgRect(t,s,i+l,n,h,a)},_getFillAttributes:function(t){var e=t&&"string"==typeof t?new b.Color(t):"";return e&&e.getSource()&&1!==e.getAlpha()?'opacity="'+e.getAlpha()+'" fill="'+e.setAlpha(1).toRgb()+'"':'fill="'+t+'"'},_getSVGLineTopOffset:function(t){for(var e,i=0,n=0;n<t;n++)i+=this.getHeightOfLine(n);return e=this.getHeightOfLine(n),{lineTop:i,offset:(this._fontSizeMult-this._fontSizeFraction)*e/(this.lineHeight*this._fontSizeMult)}},getSvgStyles:function(t){return b.Object.prototype.getSvgStyles.call(this,t)+" white-space: pre;"}})}(),function(t){var e=t.fabric||(t.fabric={});e.Textbox=e.util.createClass(e.IText,e.Observable,{type:"textbox",minWidth:20,dynamicMinWidth:2,__cachedLines:null,lockScalingFlip:!0,noScaleCache:!1,_dimensionAffectingProps:e.Text.prototype._dimensionAffectingProps.concat("width"),_wordJoiners:/[ \t\r]/,splitByGrapheme:!1,initDimensions:function(){this.__skipDimension||(this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.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;s<t.graphemeLines.length;s++)"\n"===t.graphemeText[n]&&s>0?(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],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||h<e))for(var l in i[a][h])return!1;return!0},_getStyleDeclaration:function(t,e){if(this._styleMap&&!this.isWrapping){var i=this._styleMap[t];if(!i)return null;t=i.line,e=i.offset+e}return this.callSuper("_getStyleDeclaration",t,e)},_setStyleDeclaration:function(t,e,i){var n=this._styleMap[t];t=n.line,e=n.offset+e,this.styles[t][e]=i},_deleteStyleDeclaration:function(t,e){var i=this._styleMap[t];t=i.line,e=i.offset+e,delete this.styles[t][e]},_getLineStyle:function(t){var e=this._styleMap[t];return!!this.styles[e.line]},_setLineStyle:function(t){var e=this._styleMap[t];this.styles[e.line]={}},_wrapText:function(t,e){var i,n=[];for(this.isWrapping=!0,i=0;i<t.length;i++)n=n.concat(this._wrapLine(t[i],i,e));return this.isWrapping=!1,n},_measureWord:function(t,e,i){var n,r=0;i=i||0;for(var s=0,o=t.length;s<o;s++)r+=this._getGraphemeBox(t[s],e,s+i,n,!0).kernedWidth,n=t[s];return r},_wrapLine:function(t,i,n,r){var s=0,o=this.splitByGrapheme,a=[],h=[],l=o?e.util.string.graphemeSplit(t):t.split(this._wordJoiners),c="",u=0,d=o?"":" ",f=0,g=0,m=0,p=!0,_=this._getWidthOfCharSpacing();r=r||0,0===l.length&&l.push([]),n-=r;for(var v=0;v<l.length;v++)c=o?l[v]:e.util.string.graphemeSplit(l[v]),f=this._measureWord(c,i,u),u+=c.length,(s+=g+f-_)>n&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},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<n.length;s++)r[s]=n[s].join("");return i.lines=r,i.graphemeLines=n,i},getMinWidth:function(){return Math.max(this.minWidth,this.dynamicMinWidth)},_removeExtraneousStyles:function(){var t={};for(var e in this._styleMap)this._textLines[e]&&(t[this._styleMap[e].line]=1);for(var e in this.styles)t[e]||delete this.styles[e]},toObject:function(t){return this.callSuper("toObject",["minWidth","splitByGrapheme"].concat(t))}}),e.Textbox.fromObject=function(t,i){return e.Object._fromObject("Textbox",t,i,"text")}}(e),function(){var t=b.controlsUtils,e=t.scaleSkewCursorStyleHandler,i=t.scaleCursorStyleHandler,n=t.scalingEqually,r=t.scalingYOrSkewingX,s=t.scalingXOrSkewingY,o=t.scaleOrSkewActionName,a=b.Object.prototype.controls;if(a.ml=new b.Control({x:-.5,y:0,cursorStyleHandler:e,actionHandler:s,getActionName:o}),a.mr=new b.Control({x:.5,y:0,cursorStyleHandler:e,actionHandler:s,getActionName:o}),a.mb=new b.Control({x:0,y:.5,cursorStyleHandler:e,actionHandler:r,getActionName:o}),a.mt=new b.Control({x:0,y:-.5,cursorStyleHandler:e,actionHandler:r,getActionName:o}),a.tl=new b.Control({x:-.5,y:-.5,cursorStyleHandler:i,actionHandler:n}),a.tr=new b.Control({x:.5,y:-.5,cursorStyleHandler:i,actionHandler:n}),a.bl=new b.Control({x:-.5,y:.5,cursorStyleHandler:i,actionHandler:n}),a.br=new b.Control({x:.5,y:.5,cursorStyleHandler:i,actionHandler:n}),a.mtr=new b.Control({x:0,y:-.5,actionHandler:t.rotationWithSnapping,cursorStyleHandler:t.rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:"rotate"}),b.Textbox){var h=b.Textbox.prototype.controls={};h.mtr=a.mtr,h.tr=a.tr,h.br=a.br,h.tl=a.tl,h.bl=a.bl,h.mt=a.mt,h.mb=a.mb,h.mr=new b.Control({x:.5,y:0,actionHandler:t.changeWidth,cursorStyleHandler:e,actionName:"resizing"}),h.ml=new b.Control({x:-.5,y:0,actionHandler:t.changeWidth,cursorStyleHandler:e,actionName:"resizing"})}}()},192:()=>{},898:()=>{},245:()=>{}},Je={};function $e(t){var e=Je[t];if(void 0!==e)return e.exports;var i=Je[t]={exports:{}};return Ze[t](i,i.exports,$e),i.exports}$e.d=(t,e)=>{for(var i in e)$e.o(e,i)&&!$e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},$e.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Qe={};(()=>{let t;$e.d(Qe,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?$e(653).fabric:{version:"5.2.1"}})();var ti,ei,ii,ni,ri=Qe.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"}(ti||(ti={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(ei||(ei={})),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"}(ii||(ii={})),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"}(ni||(ni={}));const si=t=>"number"==typeof t&&!Number.isNaN(t),oi=t=>"string"==typeof t;var ai,hi,li,ci,ui,di,fi,gi,mi,pi,_i;!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"}(ui||(ui={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(di||(di={}));let vi=class{get mediaType(){return new Map([["rect",ti.DIMT_RECTANGLE],["quad",ti.DIMT_QUADRILATERAL],["text",ti.DIMT_TEXT],["arc",ti.DIMT_ARC],["image",ti.DIMT_IMAGE],["polygon",ti.DIMT_POLYGON],["line",ti.DIMT_LINE],["group",ti.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ye(this,hi,"f")){case ei.DIS_DEFAULT:return"default";case ei.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"===Ye(this,li,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ye(this,li,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),He(this,li,t,"f")}get coordinateBase(){return Ye(this,li,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(ai.add(this),hi.set(this,void 0),li.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&&!si(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(ei.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(ei.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(ei.DIS_SELECTED):this.setState(ei.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){He(this,hi,t,"f")}getState(){return Ye(this,hi,"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 o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u<d?(v=a/l,g=t+this.get("x")*v,m=e+this.get("y")*v+(h-c*v)/2,p=r+this.get("x")*v,_=s+this.get("y")*v+(h-c*v)/2):(v=h/c,g=t+this.get("x")*v+(a-l*v)/2,m=e+this.get("y")*v,p=r+this.get("x")*v+(a-l*v)/2,_=s+this.get("y")*v);else if("cover"===f)if(u<d){v=h/c;let i=this.get("x")*v-(l*v-a)/2;i=Math.max(i,0),i=Math.min(i,a),g=t+i,m=e+this.get("y")*v,p=r+i,_=s+this.get("y")*v}else{v=a/l;let i=this.get("y")*v-(c*v-h)/2;i=Math.max(i,0),i=Math.min(i,h),g=t+this.get("x")*v,m=e+i,p=r+this.get("x")*v,_=s+i}n.itemClientX=Math.round(g),n.itemClientY=Math.round(m),n.itemPageX=Math.round(p),n.itemPageY=Math.round(_)}for(let t of Object.getOwnPropertyNames(n))Object.defineProperty(i,t,{value:n[t],writable:!0});e&&e.apply(this,[i])},n.set(e,r),this._fabricObject.on("dblclick"===i?"mousedblclick":i,r))}on(t,e){this._on(t,e)}_off(t,e){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&&(n.delete(e),this._fabricObject.off("dblclick"===i?"mousedblclick":i,r))}off(t,e){this._off(t,e)}_setEditable(t){const e=this._fabricObject;t?(e.selectable=!0,e.hasControls=!0,e.hoverCursor=null):(e.selectable=!1,e.hasControls=!1,e.hoverCursor="default")}hasNote(t){return this.mapNoteName_Content.has(t)}addNote(t,e){if(this.hasNote(t.name)&&!e)throw new Error("A note with the same name already exists, please use a different name.");const i=t.content?JSON.parse(JSON.stringify(t.content)):t.content;this.mapNoteName_Content.set(t.name,[i])}getNote(t){const e=this.mapNoteName_Content.get(t);return e?1===e.length?{name:t,content:e[0]?JSON.parse(JSON.stringify(e[0])):e[0]}:{name:t,content:JSON.parse(JSON.stringify(e))}:null}getNotes(){const t=[];for(let e of this.mapNoteName_Content){let i=1===e[1].length?e[1][0]:e[1];i=i?JSON.parse(JSON.stringify(i)):i,t.push({name:e[0],content:i})}return t}updateNote(t,e,i){const n=this.mapNoteName_Content.get(t);if(!n)throw new Error("The note name does not exist.");i||(n.length=0),e=e?JSON.parse(JSON.stringify(e)):e,n.push(e)}deleteNote(t){this.mapNoteName_Content.delete(t)}clearNotes(){this.mapNoteName_Content.clear()}set(t,e){if(!this.extendSet(t,e))if("x"===t){const t=this._fabricObject.group;t?(this._fabricObject.set("left",e-t.left-t.width/2),t.addWithUpdate()):this._fabricObject.set("left",e)}else if("y"===t){const t=this._fabricObject.group;t?(this._fabricObject.set("top",e-t.top-t.height/2),t.addWithUpdate()):this._fabricObject.set("top",e)}else"styleId"===t?this.styleId=e:this._fabricObject.set(t,e);["vertices","startPoint","endPoint","x","y","left","top","width","height","scaleX","scaleY","skewX","skewY","padding","angle","strokeWidth"].includes(t)&&this._fabricObject.setCoords()}get(t){let e=this.extendGet(t);if(void 0===e)if("x"===t){const t=this._fabricObject.group;e=t?this._fabricObject.get("left")+t.left+t.width/2:this._fabricObject.get("left")}else if("y"===t){const t=this._fabricObject.group;e=t?this._fabricObject.get("top")+t.top+t.height/2:this._fabricObject.get("top")}else e="scaledWidth"===t?this._fabricObject.getScaledWidth():"scaledHeight"===t?this._fabricObject.getScaledHeight():["type","mediaType"].includes(t)?this.mediaType:"state"===t?this.getState():"styleId"===t?this.styleId:"drawingLayerId"===t?this.drawingLayerId:this._fabricObject.get(t);return e}remove(){this._drawingLayer&&this._drawingLayer.removeDrawingItems([this])}convertPropFromImageToView(t){if("number"!=typeof t)throw new TypeError("Invalid value.");return t*Ye(this,ai,"m",ci).call(this)}convertPropFromViewToImage(t){if("number"!=typeof t)throw new TypeError("Invalid value.");return t/Ye(this,ai,"m",ci).call(this)}_setLineWidth(t){if(this._drawingLayer)if("view"===this.coordinateBase)this.set("strokeWidth",this.convertPropFromViewToImage(t));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("strokeWidth",t)}}_getLineWidth(){if(this._drawingLayer){if("view"===this.coordinateBase)return this.convertPropFromImageToView(this.get("strokeWidth"));if("image"===this.coordinateBase)return this.get("strokeWidth");throw new Error("Invalid 'coordinateBase'.")}}_setFontSize(t){if(this._drawingLayer)if("view"===this.coordinateBase)this.set("fontSize",this.convertPropFromViewToImage(t));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("fontSize",t)}}_getFontSize(){if(this._drawingLayer){if("view"===this.coordinateBase)return this.convertPropFromImageToView(this.get("fontSize"));if("image"===this.coordinateBase)return this.get("fontSize");throw new Error("Invalid 'coordinateBase'.")}}};hi=new WeakMap,li=new WeakMap,ai=new WeakSet,ci=function(){const t=this._drawingLayer;if(!t)return 1;const e=t.width,i=t.height,{width:n,height:r}=t.fabricCanvas.wrapperEl.getBoundingClientRect();if(n<=0||r<=0)throw new Error("Unable to get drawing layer dimensions. Layer may not be rendered on the page.");const s=n/e,o=r/i,a=t._getObjectFit();let h=1;return"contain"===a?h=s<o?n/e:r/i:"cover"===a&&(h=s<o?r/i:n/e),h},vi.arrMediaTypes=["rect","arc","polygon","image","text","line","quad"],vi.mapItemType=new Map([[ui.ARC,"arc"],[ui.IMAGE,"image"],[ui.LINE,"line"],[ui.POLYGON,"polygon"],[ui.QUAD,"quad"],[ui.RECT,"rect"],[ui.TEXT,"text"],[ui.GROUP,"group"]]),vi.arrStyleSelectors=["default","selected"],vi.mapItemState=new Map([[di.DEFAULT,"default"],[di.SELECTED,"selected"]]);class yi extends vi{constructor(t,e){if(super(null,e),fi.set(this,void 0),!P(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new ri.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),He(this,fi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="rect"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth"))),this.set("height",this.convertPropFromViewToImage(this.get("scaledHeight")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth"))),this.set("height",this.convertPropFromImageToView(this.get("scaledHeight")))}setPosition(t){this.setRect(t)}getPosition(){return this.getRect()}updatePosition(){Ye(this,fi,"f")&&this.setRect(Ye(this,fi,"f"))}setRect(t){if(!P(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width)),this.set("height",this.convertPropFromViewToImage(t.height));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width),this.set("height",t.height)}this._drawingLayer.renderAll()}else He(this,fi,JSON.parse(JSON.stringify(t)),"f")}getRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ye(this,fi,"f")?JSON.parse(JSON.stringify(Ye(this,fi,"f"))):null}}function wi(t,e,i){let n=i.points[this.pointIndex].x-i.pathOffset.x,r=i.points[this.pointIndex].y-i.pathOffset.y;return ri.util.transformPoint({x:n,y:r},i.calcTransformMatrix())}function Ci(t){let e=new ri.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new ri.Point(t.width+e.x,t.height+e.y)}function Ei(t,e,i,n){let r=e.target,s=r.controls[r.__corner],o=r.toLocalPoint(new ri.Point(i,n),"center","center"),a=Ci(r),h=r._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+r.pathOffset.x,y:o.y*a.y/h.y+r.pathOffset.y};return r.points[s.pointIndex]=l,ri.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:n}}),!0}function Si(t,e){return function(i,n,r,s){let o=n.target,a=ri.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,n,r,s);o._setPositionDimensions({});let l=Ci(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}fi=new WeakMap;class bi extends vi{constructor(t,e){if(super(null,e),gi.set(this,void 0),!M(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new ri.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let n=i.points.length-1;i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new ri.Control({positionHandler:wi,actionHandler:Si(i>0?i-1:n,Ei),actionName:"modifyPolygon",pointIndex:i}),t},{}),He(this,gi,JSON.parse(JSON.stringify(t)),"f"),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 ri.Control({positionHandler:wi,actionHandler:Si(n>0?n-1:i,Ei),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=ri.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(){Ye(this,gi,"f")&&this.setPolygon(Ye(this,gi,"f"))}setPolygon(t){if(!M(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 He(this,gi,JSON.parse(JSON.stringify(t)),"f")}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 Ye(this,gi,"f")?JSON.parse(JSON.stringify(Ye(this,gi,"f"))):null}}gi=new WeakMap;mi=new WeakMap,pi=new WeakMap;const Ti=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;n<t.length;n++){let r=t[n][e];void 0!==r&&r.length>i&&(i=r.length)}if(-1===i)break;for(let n=0;n<t.length;n++){if(e>=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<t.length;i++)e=e.concat(...t[i],i===t.length-1?"":"\n");return e})(e)};class Ii extends vi{constructor(t,e,i){if(super(null,i),_i.set(this,void 0),!oi(t))throw new TypeError("Invalid 'text'.");if(!P(e))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new ri.Textbox(Ti(t),{left:e.x,top:e.y,width:e.width})),this._text=t,He(this,_i,JSON.parse(JSON.stringify(e)),"f"),this._mediaType="text"}extendSet(t,e){if("text"===t)return this._text=e,this._fabricObject.set("text",Ti(e)),!0}extendGet(t){if("text"===t)return this._text}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth")))}setPosition(t){this.setTextRect(t)}getPosition(){return this.getTextRect()}updatePosition(){Ye(this,_i,"f")&&this.setTextRect(Ye(this,_i,"f"))}setText(t){if(!oi(t))throw new TypeError("Invalid 'text'.");this.set("text",t)}getText(){return this.get("text")}setTextRect(t){if(!P(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width)}this._drawingLayer.renderAll()}else He(this,_i,JSON.parse(JSON.stringify(t)),"f")}getTextRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ye(this,_i,"f")?JSON.parse(JSON.stringify(Ye(this,_i,"f"))):null}}var xi,Oi;_i=new WeakMap;xi=new WeakMap;class Ri extends bi{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Oi.set(this,void 0),!F(t))throw new TypeError("Invalid 'quad'.");He(this,Oi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Ye(this,Oi,"f")&&this.setQuad(Ye(this,Oi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!F(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 He(this,Oi,JSON.parse(JSON.stringify(t)),"f")}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 Ye(this,Oi,"f")?JSON.parse(JSON.stringify(Ye(this,Oi,"f"))):null}}Oi=new WeakMap;class Ai extends vi{constructor(t){super(new ri.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(ei.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(ei.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 Di=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Li=t=>!!oi(t)&&""!==t,Mi=t=>!(!Di(t)||"id"in t&&!si(t.id)||"lineWidth"in t&&!si(t.lineWidth)||"fillStyle"in t&&!Li(t.fillStyle)||"strokeStyle"in t&&!Li(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Li(t.fontFamily)||"fontSize"in t&&!si(t.fontSize));class Fi{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(P(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!R(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Pi,ki;class Ni{constructor(){Pi.set(this,new Map),ki.set(this,!1)}get disposed(){return Ye(this,ki,"f")}on(t,e){t=t.toLowerCase();const i=Ye(this,Pi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ye(this,Pi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ye(this,Pi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Ye(this,Pi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Ye(this,Pi,"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 o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){He(this,ki,!0,"f")}}function Bi(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 ji(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Ui(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))}Pi=new WeakMap,ki=new WeakMap;const Vi=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};class Gi{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 Gi.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 Gi.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Gi.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Wi,Yi,Hi,Xi,zi,qi,Ki,Zi,Ji,$i,Qi,tn,en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr;class _r{static createDrawingStyle(t){if(!Mi(t))throw new Error("Invalid style definition.");let e,i=_r.USER_START_STYLE_ID;for(;Ye(_r,Wi,"f",Yi).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Ye(_r,Wi,"f",Hi))n.hasOwnProperty(t)||(n[t]=Ye(_r,Wi,"f",Hi)[t]);return Ye(_r,Wi,"f",Yi).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ye(_r,Wi,"f",Yi).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(Ye(_r,Wi,"f",Yi).values())))}static _updateDrawingStyle(t,e){if(!Mi(e))throw new Error("Invalid style definition.");const i=Ye(_r,Wi,"f",Yi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Wi=_r,_r.STYLE_BLUE_STROKE=1,_r.STYLE_GREEN_STROKE=2,_r.STYLE_ORANGE_STROKE=3,_r.STYLE_YELLOW_STROKE=4,_r.STYLE_BLUE_STROKE_FILL=5,_r.STYLE_GREEN_STROKE_FILL=6,_r.STYLE_ORANGE_STROKE_FILL=7,_r.STYLE_YELLOW_STROKE_FILL=8,_r.STYLE_BLUE_STROKE_TRANSPARENT=9,_r.STYLE_GREEN_STROKE_TRANSPARENT=10,_r.STYLE_ORANGE_STROKE_TRANSPARENT=11,_r.USER_START_STYLE_ID=1024,Yi={value:new Map([[_r.STYLE_BLUE_STROKE,{id:_r.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[_r.STYLE_GREEN_STROKE,{id:_r.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}],[_r.STYLE_ORANGE_STROKE,{id:_r.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}],[_r.STYLE_YELLOW_STROKE,{id:_r.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[_r.STYLE_BLUE_STROKE_FILL,{id:_r.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}],[_r.STYLE_GREEN_STROKE_FILL,{id:_r.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}],[_r.STYLE_ORANGE_STROKE_FILL,{id:_r.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}],[_r.STYLE_YELLOW_STROKE_FILL,{id:_r.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}],[_r.STYLE_BLUE_STROKE_TRANSPARENT,{id:_r.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[_r.STYLE_GREEN_STROKE_TRANSPARENT,{id:_r.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[_r.STYLE_ORANGE_STROKE_TRANSPARENT,{id:_r.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&&(ri.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ri.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),ri.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ri.Object.prototype.transparentCorners=!1,ri.Object.prototype.cornerSize=20,ri.Object.prototype.touchCornerSize=100,ri.Object.prototype.cornerColor="rgb(254,142,20)",ri.Object.prototype.cornerStyle="circle",ri.Object.prototype.strokeUniform=!0,ri.Object.prototype.hasBorders=!1,ri.Canvas.prototype.containerClass="",ri.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=ri.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=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 h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},ri.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;i<t.touches.length;i++){let n=t.touches[i];if(e=this.findTarget(n),e)break}100===this.id&&!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),100===this.id&&e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();let i=this.upperCanvasEl,n=this._getEventPrefix();ri.util.addListener(ri.document,"touchend",this._onTouchEnd,{passive:!1}),ri.util.addListener(ri.document,"touchmove",this._onMouseMove,{passive:!1}),ri.util.removeListener(i,n+"down",this._onMouseDown)},ri.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 o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?ri.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;y<c.length;y++)u=a?c[y]:ri.util.string.graphemeSplit(c[y]),g=this._measureWord(u,e,d),d+=u.length,(o+=m+g-v)>i&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class vr{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 ri.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.fabricCanvas.id=e,this.id=e,e){case vr.DDN_LAYER_ID:n=_r.getDrawingStyle(_r.STYLE_BLUE_STROKE),r=_r.getDrawingStyle(_r.STYLE_BLUE_STROKE_FILL);break;case vr.DBR_LAYER_ID:n=_r.getDrawingStyle(_r.STYLE_ORANGE_STROKE),r=_r.getDrawingStyle(_r.STYLE_ORANGE_STROKE_FILL);break;case vr.DLR_LAYER_ID:n=_r.getDrawingStyle(_r.STYLE_GREEN_STROKE),r=_r.getDrawingStyle(_r.STYLE_GREEN_STROKE_FILL);break;default:n=_r.getDrawingStyle(_r.STYLE_YELLOW_STROKE),r=_r.getDrawingStyle(_r.STYLE_YELLOW_STROKE_FILL)}for(let t of vi.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 _r.getDrawingStyle(t.styleId);return _r.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=_r.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=_r.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=_r.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,_r.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,_r.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 vi))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 vi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=_r.getDrawingStyle(t.styleId);else{s=_r.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,_r.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,_r.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 vi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=_r.getDrawingStyle(t.styleId);else{s=_r.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,_r.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,_r.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 o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;e<n.length;e++)if(t._zIndex<n[e].getDrawingItem()._zIndex){a=e;break}this._arrDrwaingItem.push(t),this._arrFabricObject.push(i),this._visible?i.visible=!0:i.visible=!1,this.fabricCanvas.insertAt(i,a,!1)}addDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");if("viewer"===this.mode)t._setEditable(!1);else{if("editor"!==this.mode)throw new Error("Illegal 'mode'.");t._setEditable(!0)}this._addDrawingItem(t),t.updatePosition()}addDrawingItems(t){for(let e of t)this.addDrawingItem(e)}removeDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");if(!this.hasDrawingItem(t))return;if(t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,"group"===t._mediaType){const e=t.getChildDrawingItems();for(let t of e)t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,t._mapState_StyleId.clear()}else t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,t._mapState_StyleId.clear();const e=t._getFabricObject();"selected"===t.styleSelector&&(e.group?e.group.removeWithUpdate(e):this.fabricCanvas._activeObject=null,t.setState(ei.DIS_DEFAULT)),this.fabricCanvas.remove(e),this._arrDrwaingItem.splice(this._arrDrwaingItem.indexOf(t),1),this._arrFabricObject.splice(this._arrFabricObject.indexOf(e),1)}removeDrawingItems(t){for(let e of t)this.removeDrawingItem(e)}setDrawingItems(t){this.clearDrawingItems(),this.addDrawingItems(t)}getDrawingItems(t){return t&&"function"==typeof t?this._arrDrwaingItem.filter(t):Array.from(this._arrDrwaingItem)}getSelectedDrawingItems(){const t=this.fabricCanvas.getActiveObjects(),e=[];for(let i of t)this._arrFabricObject.includes(i)&&e.push(i.getDrawingItem());return e}hasDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");return this._arrDrwaingItem.includes(t)}clearDrawingItems(){this.removeDrawingItems(Array.from(this._arrDrwaingItem))}_setDefaultStyle(t,e,i){e?e.forEach(t=>t.toLowerCase()):e=vi.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=vi.arrStyleSelectors;const n=_r.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&ti.DIMT_RECTANGLE&&n.push("rect"),i&ti.DIMT_QUADRILATERAL&&n.push("quad"),i&ti.DIMT_TEXT&&n.push("text"),i&ti.DIMT_ARC&&n.push("arc"),i&ti.DIMT_IMAGE&&n.push("image"),i&ti.DIMT_POLYGON&&n.push("polygon"),i&ti.DIMT_LINE&&n.push("line");const r=[];e&ei.DIS_DEFAULT&&r.push("default"),e&ei.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)}}vr.DDN_LAYER_ID=1,vr.DBR_LAYER_ID=2,vr.DLR_LAYER_ID=3,vr.USER_DEFINED_LAYER_BASE_ID=100,vr.TIP_LAYER_ID=999;class yr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new vr(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 wr extends Ii{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<i;e++)t+=this.getHeightOfLine(e);return t+2*this.paddingTop},this._fabricObject._getTopOffset=function(){return-this.height/2+this.getHeightOfLine(0)*(1-1/this.lineHeight)/2+this.paddingTop},this.set("backgroundColor","rgba(50, 50, 52, .8)"),this.set("lineHeight",1.3),this.set("textAlign","center")}setDuration(t){He(this,Xi,t,"f"),Ye(this,zi,"f")&&clearTimeout(Ye(this,zi,"f")),Ye(this,Xi,"f")>=0&&He(this,zi,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},Ye(this,Xi,"f")),"f")}getDuration(){return Ye(this,Xi,"f")}}Xi=new WeakMap,zi=new WeakMap;class Cr{constructor(){qi.add(this),Ki.set(this,void 0),Zi.set(this,void 0),Ji.set(this,void 0),$i.set(this,!0),this._drawingLayerManager=new yr}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=vr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==vr.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(t<vr.USER_DEFINED_LAYER_BASE_ID)throw new Error(`The drawing layer with id ${t} is not defined by users.`);this.deleteDrawingLayer(t)}_clearDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t)this.deleteDrawingLayer(e.getId())}clearUserDefinedDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t){const t=e.getId();t<vr.USER_DEFINED_LAYER_BASE_ID||this.deleteUserDefinedDrawingLayer(t)}}getDrawingLayer(t){if(t==vr.TIP_LAYER_ID)return null;return this._drawingLayerManager.getDrawingLayer(t)||([vr.DDN_LAYER_ID,vr.DBR_LAYER_ID,vr.DLR_LAYER_ID].includes(t)?this._createDrawingLayer(t):null)}getAllDrawingLayers(){return this._drawingLayerManager.getAllDrawingLayers().filter(t=>t.getId()>=0&&t.getId()!==vr.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(!(Di(e=t)&&L(e.topLeftPoint)&&si(e.width))||e.width<=0||!si(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;He(this,Ki,JSON.parse(JSON.stringify(t)),"f"),Ye(this,Ki,"f").coordinateBase||(Ye(this,Ki,"f").coordinateBase="view"),He(this,Ji,t.duration,"f"),Ye(this,qi,"m",nn).call(this)}getTipConfig(){return Ye(this,Ki,"f")?Ye(this,Ki,"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()),He(this,$i,t,"f")}isTipVisible(){return Ye(this,$i,"f")}updateTipMessage(t){if(!Ye(this,Ki,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=_r.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(vr.TIP_LAYER_ID)||this._createDrawingLayer(vr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ye(this,qi,"m",Qi).call(this,t,Ye(this,Ki,"f").topLeftPoint.x,Ye(this,Ki,"f").topLeftPoint.y,Ye(this,Ki,"f").width,Ye(this,Ki,"f").coordinateBase,this._tipStyleId),Ye(this,qi,"m",tn).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ye(this,$i,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ye(this,Zi,"f")&&clearTimeout(Ye(this,Zi,"f")),Ye(this,Ji,"f")>=0&&He(this,Zi,setTimeout(()=>{Ye(this,qi,"m",en).call(this)},Ye(this,Ji,"f")),"f")}}Ki=new WeakMap,Zi=new WeakMap,Ji=new WeakMap,$i=new WeakMap,qi=new WeakSet,Qi=function(t,e,i,n,r,s){const o=new wr(t,e,i,n,s);return o.coordinateBase=r,o},tn=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},en=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},nn=function(){if(!this._tip)return;const t=Ye(this,Ki,"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 Er extends HTMLElement{constructor(){super(),rn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),He(this,rn,e,"f");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 Ye(this,rn,"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())}}rn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Er);class Sr extends Cr{static get engineResourcePath(){const t=B(Bt.engineResourcePaths);return"DCV"===Bt._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Sr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Sr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Sr.engineResourcePath)}static async createInstance(t){const e=new Sr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Sr.engineResourcePath)),await e.setUIElement(t||Sr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ye(this,gn,"f")){if(He(this,gn,t,"f"),Ye(this,sn,"m",_n).call(this))He(this,ln,null,"f"),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"),!Ye(this,ln,"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("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(We.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),He(this,ln,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ye(this,sn,"m",_n).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 Ye(this,gn,"f")}get disposed(){return Ye(this,pn,"f")}constructor(){super(),sn.add(this),on.set(this,void 0),an.set(this,void 0),hn.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",ln.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,this._poweredBy=null,cn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,un.set(this,!1),dn.set(this,!1),fn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ye(this,sn,"m",En).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()&&Ye(this,sn,"m",Cn).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Sr._onLog&&Sr._onLog("window resize event triggered."),Ye(this,fn,"f").width===document.documentElement.clientWidth&&Ye(this,fn,"f").height===document.documentElement.clientHeight||(Ye(this,fn,"f").width=document.documentElement.clientWidth,Ye(this,fn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},gn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ye(this,sn,"m",_n).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 o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.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()},mn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed||e&&e._isPauseScan)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach(t=>Sr._transformCoordinates(t,i,n,r,s,o,a));const c=new Ri({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}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ye(this,mn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case at.CRIT_ORIGINAL_IMAGE:break;case at.CRIT_BARCODE:m=this.getDrawingLayer(vr.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,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,_r.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case at.CRIT_TEXT_LINE:m=this.getDrawingLayer(vr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,_r.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case at.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(vr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===mt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],_r.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case at.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(vr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===mt.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],_r.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case at.CRIT_PARSED_RESULT:case at.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}if(t.decodedBarcodesResult)for(let e=0;e<t.decodedBarcodesResult.barcodeResultItems.length;e++)t.decodedBarcodesResult.barcodeResultItems[e].location.points.forEach(t=>Sr._transformCoordinates(t,h,l,c,u,d,f));if(t.recognizedTextLinesResult)for(let e=0;e<t.recognizedTextLinesResult.textLineResultItems.length;e++)t.recognizedTextLinesResult.textLineResultItems[e].location.points.forEach(t=>Sr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult){if(t.processedDocumentResult.detectedQuadResultItems)for(let e=0;e<t.processedDocumentResult.detectedQuadResultItems.length;e++)t.processedDocumentResult.detectedQuadResultItems[e].location.points.forEach(t=>Sr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult.deskewedImageResultItems)for(let e=0;e<t.processedDocumentResult.deskewedImageResultItems.length;e++)t.processedDocumentResult.deskewedImageResultItems[e].location.points.forEach(t=>Sr._transformCoordinates(t,h,l,c,u,d,f))}}},pn.set(this,!1),this.eventHandler=new Ni,this.eventHandler.on("content:updated",()=>{Ye(this,on,"f")&&clearTimeout(Ye(this,on,"f")),He(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),"f")}),this.eventHandler.on("videoEl:resized",()=>{Ye(this,an,"f")&&clearTimeout(Ye(this,an,"f")),He(this,an,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Vi(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),Ye(this,sn,"m",_n).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("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(We.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),He(this,ln,t,"f");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._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||Ye(this,sn,"m",_n).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['<option class="dce-opt-gotResolution" value="got"></option>','<option data-width="1920" data-height="1080">ask 1920x1080</option>','<option data-width="1280" data-height="720">ask 1280x720</option>','<option data-width="640" data-height="480">ask 640x480</option>'].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ye(this,sn,"m",_n).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['<option class="dlr-opt-gotMinLtr" value="got"></option>','<option value="0" selected>any letter</option>','<option value="3">3+ letters</option>','<option value="5">5+ letters</option>','<option value="8">8+ letters</option>','<option value="12">12+ letters</option>','<option value="17">17+ letters</option>','<option value="30">30+ letters</option>','<option value="50">50+ letters</option>','<option value="80">80+ letters</option>','<option value="120">120+ letters</option>'].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ye(this,sn,"m",En).call(this),Ye(this,sn,"m",_n).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ye(this,sn,"m",_n).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;Sr._onLog&&Sr._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)}Ye(this,fn,"f").width=document.documentElement.clientWidth,Ye(this,fn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Ye(this,sn,"m",_n).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ye(this,sn,"m",En).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,He(this,ln,null,"f"),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 Ye(this,ln,"f")}isVideoLoaded(){return!(!Ye(this,ln,"f")||!this.cameraEnhancer)&&4==Ye(this,ln,"f").readyState}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ye(this,ln,"f"))return;if(Ye(this,ln,"f").style.objectFit=t,Ye(this,sn,"m",_n).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();Ye(this,sn,"m",Sn).call(this,e,i),Ye(this,sn,"m",vn).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(Ye(this,sn,"m",_n).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,o="contain"):(r=null===(t=Ye(this,ln,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ye(this,ln,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){R(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):P(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=Fi.convert(this.scanRegion,t.width,t.height,this);He(this,cn,e,"f"),Ye(this,hn,"f")&&clearTimeout(Ye(this,hn,"f")),He(this,hn,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ye(this,sn,"m",vn).call(this,t,e),Ye(this,sn,"m",Sn).call(this,t,e)},0),"f")}getConvertedRegion(){return Ye(this,cn,"f")}setScanRegion(t){if(null!=t&&!R(t)&&!P(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("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ye(this,ln,"f").videoWidth,i=Ye(this,ln,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s<e/i?(o=s/i,a.x=Math.floor((e-r/o)/2),a.y=0,a.width=Math.ceil(r/o),a.height=i):(o=r/e,a.x=0,a.y=Math.floor((i-s/o)/2),a.width=e,a.height=Math.ceil(s/o))),null==t?void 0:t.inPixels)return a;const h=a;return h.x=Math.ceil(h.x/i*100),h.y=Math.ceil(h.y/e*100),h.width=Math.floor(h.width/e*100),h.height=Math.floor(h.height/i*100),h.isMeasuredInPercentage=!0,a}setScanRegionMask(t,e,i,n){this._drawingLayerOfMask||(this._drawingLayerOfMask=this._createDrawingLayer(-2),this.isScanRegionMaskVisible()||Ye(this,sn,"m",wn).call(this)),this.clearScanRegionMask(),this._maskBackRectStyleId||(this._maskBackRectStyleId=_r.createDrawingStyle({paintMode:"fill",fillStyle:this.regionMaskFillStyle,lineWidth:0})),this._maskCenterRectStyleId||(this._maskCenterRectStyleId=_r.createDrawingStyle({paintMode:"stroke",strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth}));const r=this._drawingLayerOfMask.width,s=this._drawingLayerOfMask.height,o=new yi({x:0,y:0,width:r,height:s},this._maskBackRectStyleId),a=new yi({x:-r/2,y:-s/2+e,width:t,height:n}),h=new yi({x:-r/2+t+i,y:-s/2+e,width:r-t-i<0?0:r-t-i,height:n}),l=new yi({x:-r/2,y:-s/2,width:r,height:e}),c=new yi({x:-r/2,y:-s/2+e+n,width:r,height:s-e-n<0?0:s-e-n});a.set("strokeWidth",0),h.set("strokeWidth",0),l.set("strokeWidth",0),c.set("strokeWidth",0);const u=new Ai([a,h,l,c])._getFabricObject();o.set("clipPath",u);const d=new yi({x:t,y:e,width:i-this.regionMaskLineWidth,height:n-this.regionMaskLineWidth},this._maskCenterRectStyleId);this._drawingLayerOfMask.addDrawingItems([o,d])}clearScanRegionMask(){this._drawingLayerOfMask&&this._drawingLayerOfMask.clearDrawingItems()}deleteScanRegionMask(){this._drawingLayerOfMask&&this.deleteDrawingLayer(this._drawingLayerOfMask.getId())}_setScanRegionMaskVisible(t){He(this,un,t,"f"),t?Ye(this,sn,"m",yn).call(this):Ye(this,sn,"m",wn).call(this)}setScanRegionMaskVisible(t){this._setScanRegionMaskVisible(t),this._userSetMaskVisible=t}isScanRegionMaskVisible(){return Ye(this,un,"f")}setScanRegionMaskStyle(t){if(!t)return;let e;t.fillStyle&&(this.regionMaskFillStyle=t.fillStyle),t.strokeStyle&&(this.regionMaskStrokeStyle=t.strokeStyle),t.lineWidth&&(this.regionMaskLineWidth=t.lineWidth),this._maskBackRectStyleId&&_r.updateDrawingStyle(this._maskBackRectStyleId,{fillStyle:this.regionMaskFillStyle}),this._maskCenterRectStyleId&&_r.updateDrawingStyle(this._maskCenterRectStyleId,{strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth});try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const i=this.getConvertedRegion();Ye(this,sn,"m",vn).call(this,e,i),Ye(this,sn,"m",Sn).call(this,e,i)}getScanRegionMaskStyle(){return{fillStyle:this.regionMaskFillStyle,strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth}}_setScanLaserVisible(t){He(this,dn,t,"f"),t?Ye(this,sn,"m",Cn).call(this):Ye(this,sn,"m",En).call(this)}setScanLaserVisible(t){this._setScanLaserVisible(t),this._userSetLaserVisible=t}isScanLaserVisible(){return Ye(this,dn,"f")}_updateVideoContainer(){if(!Ye(this,ln,"f"))return;if(Ye(this,sn,"m",_n).call(this))return;let t=1;const e=Ye(this,ln,"f").style.transform.match(/scale\((.+)\)/);e&&(t=parseFloat(e[1]));const i=this._videoContainer;if("contain"===this.videoFit&&t>1){const t=Ye(this,ln,"f").videoWidth,e=Ye(this,ln,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/r<s){let t=n/s;i.style.left="0",i.style.top=(r-t)/2/r*100+"%",i.style.width="100%",i.style.height=t/r*100+"%"}else{let t=r*s;i.style.left=(n-t)/2/n*100+"%",i.style.top="0",i.style.width=t/n*100+"%",i.style.height="100%"}}else i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%"}setPowerByMessageVisible(t){this._poweredBy&&(this._poweredBy.style.display=t?"":"none",this._poweredByVisible=t);let e=this.getUIElement();e=e.shadowRoot||e;const i=e.querySelector(".dce-mn-msg-poweredby");i&&(i.style.display=t?"":"none",this._poweredByVisible=t)}isPowerByMessageVisible(){return this._poweredByVisible}updateLayers(){let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const e=this.getConvertedRegion();Ye(this,sn,"m",Sn).call(this,t,e),this.updateDrawingLayers(t),Ye(this,sn,"m",vn).call(this,t,e)}clearAllInnerDrawingItems(){Ye(this,mn,"f").forEach(t=>t.remove()),Ye(this,mn,"f").length=0}dispose(){this._unbindUI(),He(this,pn,!0,"f")}}on=new WeakMap,an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,sn=new WeakSet,_n=function(){return"disabled"!==this._singleFrameMode},vn=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)},yn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},wn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Cn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},En=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Sn=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:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a<h?(f=s/i,l=0,c=(o-n*f)/2):(f=o/n,l=(s-i*f)/2,c=0),l+=e.x*f,c+=e.y*f,u=e.width*f,d=e.height*f;else if("cover"===r)if(a<h){f=o/n,l=e.x*f-(i*f-s)/2,l=Math.max(l,0),l=Math.min(l,s),c=e.y*f;let t=(e.x+e.width)*f-(i*f-s)/2;t=Math.max(t,0),t=Math.min(t,s),u=t-l,d=e.height*f}else{f=s/i,l=e.x*f,c=e.y*f-(n*f-o)/2,c=Math.max(c,0),c=Math.min(c,o);let t=(e.y+e.height)*f-(n*f-o)/2;t=Math.max(t,0),t=Math.min(t,o),u=e.width*f,d=t-c}else l=0,c=0,u=0,d=0;this.scanRegion?(this._divScanArea.style.left=l+this.regionMaskLineWidth*f+"px",this._divScanArea.style.top=c+this.regionMaskLineWidth*f+"px",this._divScanArea.style.width=u-this.regionMaskLineWidth*f*2+"px",this._divScanArea.style.height=d-this.regionMaskLineWidth*f*2+"px"):(this._divScanArea.style.left=l+.005*u+"px",this._divScanArea.style.top=c+.005*u+"px",this._divScanArea.style.width=u-.01*u+"px",this._divScanArea.style.height=d-.01*u+"px")},Sr._defaultUIElementURL="@engineResourcePath/dce.ui.xml";class br{static get version(){return"4.2.12-dev-20250709132053"}static get webGLSupported(){return void 0===br._webGLSupported&&(br._webGLSupported=!!document.createElement("canvas").getContext("webgl")),br._webGLSupported}get disposed(){return Ye(this,Rn,"f")}constructor(){bn.set(this,ni.RGBA),Tn.set(this,null),In.set(this,null),xn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,On.set(this,null),Rn.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)&&!br.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 o;br._onLog&&(o=Date.now(),br._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(a=Math.round(r.sx)),r.sy&&(h=Math.round(r.sy)),r.sWidth&&(l=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=ni.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(!br.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){br._onLog&&br._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<u+f||_.height<d+g)&&(_.width=u+f,_.height=d+g),t.drawImage(e,a,h,l,c,u,d,f,g),br._onLog&&br._onLog("drawImage() in context2d end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:ni.RGBA,bUseWebGL:!1}}br._onLog&&br._onLog("drawImage() in WebGL.");try{(_.width<u+f||_.height<d+g)&&(_.width=u+f,_.height=d+g,_.ctxWebGL&&_.ctxWebGL.viewport(0,0,u+f,d+g));const t=_.ctxWebGL||_.getContext("webgl",{antialias:!1})||_.getContext("experimental-webgl",{antialias:!1});if(!t){br._onLog&&br._onLog("Browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");const t=new Error("Unable to get 'WebGLRenderingContext'. Your browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");throw t.name="WebGLError",t}if(!_.ctxWebGL||p!==Ye(this,bn,"f")){_.ctxWebGL=t;const e=t=>{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="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);He(this,In,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),He(this,xn,e(t),"f"),He(this,Tn,i(t),"f"),He(this,bn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(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)},y=(t,e,o,m)=>{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,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[ni.GREY,ni.GREY32].includes(p)?1:0);let _,v,y=Gi.translate(Gi.identity(),-1,-1);y=Gi.scale(y,2,2),y=Gi.scale(y,1/t.canvas.width,1/t.canvas.height),_=Gi.translate(y,u,d),_=Gi.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=Gi.translate(Gi.identity(),1,0),v=Gi.scale(v,-1,1),v=Gi.translate(v,a/i,h/n),v=Gi.scale(v,l/i,c/n)):(v=Gi.translate(Gi.identity(),a/i,h/n),v=Gi.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,Ye(this,Tn,"f"),e),y(t,Ye(this,In,"f"),Ye(this,xn,"f"),Ye(this,Tn,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){br._onLog&&br._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return br._onLog&&br._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===ni.GREY?ni.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return br._onLog&&br._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 o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(br._onLog&&(r=Date.now(),br._onLog("transformPixelFormat(), START: "+r)),e===i)return br._onLog&&br._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[ni.RGBA,ni.RBGA,ni.GRBA,ni.GBRA,ni.BRGA,ni.BGRA];if(o.includes(e))if(i===ni.GREY){s=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4){const i=.3*t[e]+.59*t[e+1]+.11*t[e+2];s[e/4]=i}}else if(i===ni.GREY32){s=n?new Uint8Array(t):t;for(let e=0;e<t.length;e+=4){const i=.3*t[e]+.59*t[e+1]+.11*t[e+2];s[e]=i,s[e+1]=i,s[e+2]=i}}else{if(!o.includes(i))throw new Error("Unable to transform.");if(n){s=new Uint8Array(t);const n=e.indexOf("r"),r=e.indexOf("g"),o=e.indexOf("b"),a=i.indexOf("r"),h=i.indexOf("g"),l=i.indexOf("b");for(let e=0;e<t.length;e+=4)s[e+a]=t[e+n],s[e+h]=t[e+r],s[e+l]=t[e+o]}else{s=t;const n=e.indexOf("r"),r=e.indexOf("g"),o=e.indexOf("b"),a=i.indexOf("r"),h=i.indexOf("g"),l=i.indexOf("b");for(let e=0;e<t.length;e+=4){let i=[t[e],t[e+1],t[e+2]];s[e+a]=i[n],s[e+h]=i[r],s[e+l]=i[o]}}}else if(e===ni.GREY){if(i!==ni.GREY32)throw new Error("Unable to transform.");s=new Uint8Array(4*t.length);for(let e=0;e<t.length;e++)s[4*e]=t[e],s[4*e+1]=t[e],s[4*e+2]=t[e],s[4*e+3]=255}else{if(e!==ni.GREY32)throw new Error("Unable to transform.");if(i!==ni.GREY)throw new Error("Unable to transform.");s=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4)s[e/4]=t[e]}return br._onLog&&br._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),s}getImageData(t,e,i){var n,r,s,o,a;if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let h,l;if(t instanceof HTMLImageElement)h=t.naturalWidth,l=t.naturalHeight;else if(t instanceof HTMLCanvasElement)h=t.width,l=t.height;else if(t instanceof HTMLVideoElement)h=t.videoWidth,l=t.videoHeight;else{if(!(t instanceof ImageBitmap))throw Error("The type of 'source' is not supported.");h=t.width,l=t.height}let c,u=br.webGLSupported&&this.useWebGLByDefault;if(e.sx<0||e.sy<0||e.sx+e.sWidth>h||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=br._onLog)||void 0===n||n.call(br,"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)||ni.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(ni.GREY===y&&w.length<p*_||ni.RGBA===y&&w.length<p*_*4))throw new Error("Unexpected size of the 'bufferContainer'.");if(u){null===(r=br._onLog)||void 0===r||r.call(br,"getImageData() in WebGL.");let o,a=this._reusedWebGLCvs=this._reusedWebGLCvs||document.createElement("canvas");try{if(w)if(y===ni.GREY){if(v=new Uint8Array(4*p*_),o=this.drawImage(a,t,h,l,{sx:d,sy:f,sWidth:g,sHeight:m,dWidth:p,dHeight:_},{pixelFormat:y,bUseWebGL:!0,bufferContainer:v,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),v=this.transformPixelFormat(v,o.pixelFormat,y),w){if(w.length<v.length)throw new Error("Unexpected size of the 'bufferContainer'.");w.set(v)}}else o=this.drawImage(a,t,h,l,{sx:d,sy:f,sWidth:g,sHeight:m,dWidth:p,dHeight:_},{pixelFormat:y,bUseWebGL:!0,bufferContainer:w,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),v=new Uint8Array(w.buffer,0,4*p*_),v=this.transformPixelFormat(v,o.pixelFormat,y);else y===ni.GREY?((!Ye(this,On,"f")||Ye(this,On,"f").length<4*p*_)&&He(this,On,new Uint8Array(4*p*_),"f"),v=new Uint8Array(Ye(this,On,"f").buffer,0,4*p*_)):v=new Uint8Array(4*p*_),o=this.drawImage(a,t,h,l,{sx:d,sy:f,sWidth:g,sHeight:m,dWidth:p,dHeight:_},{pixelFormat:y,bUseWebGL:!0,bufferContainer:v,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),v=this.transformPixelFormat(v,o.pixelFormat,y)}catch(n){if("WebGLError"===n.name)return this.forceLoseContext(),console.warn("WebGLError: "+(null==n?void 0:n.message)),null===(s=br._onLog)||void 0===s||s.call(br,"getImageData() in WebGL failed, try again in context2d."),br._webGLSupported=!1,this.getImageData(t,e,i);throw n}}else{null===(o=br._onLog)||void 0===o||o.call(br,"getImageData() in context2d.");let e=this._reusedCvs=this._reusedCvs||document.createElement("canvas");e.width!=p&&(e.width=p),e.height!=_&&(e.height=_);let n=e.getContext("2d",{willReadFrequently:!0});if(i.isEnableMirroring?(n.save(),n.translate(p,0),n.scale(-1,1),n.drawImage(t,d,f,g,m,0,0,p,_),n.restore()):n.drawImage(t,d,f,g,m,0,0,p,_),v=new Uint8Array(n.getImageData(0,0,p,_).data.buffer),ni.GREY===y){let t=w||new Uint8Array(p*_);for(let e=0;e<v.length;e+=4)t[e/4]=Math.round((v[e]+v[e+1]+v[e+2])/3);v=t}else null==w||w.set(v)}return null===(a=br._onLog)||void 0===a||a.call(br,"getImageData() end. Costs: "+(Date.now()-c)),{data:v,pixelFormat:y,width:p,height:_,bUseWebGL:u}}convertDataToCvs(t,e,i,n){if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new TypeError("Invalid 'data'.");if("number"!=typeof e||e<=0)throw new Error("Invalid 'width'.");if("number"!=typeof i||i<=0)throw new Error("Invalid 'height'.");const r=document.createElement("canvas");let s;if(r.width=e,r.height=i,n===ni.GREY){s=new Uint8ClampedArray(4*e*i);for(let e=0;e<s.length;e+=4)s[e]=t[e/4],s[e+1]=t[e/4],s[e+2]=t[e/4],s[e+3]=255}else s=new Uint8ClampedArray(t.buffer);const o=new ImageData(s,e,i);return r.getContext("2d").putImageData(o,0,0),r}forceLoseContext(){var t;if(!this._reusedWebGLCvs)return;const e=this._reusedWebGLCvs.ctxWebGL;e&&!e.isContextLost()&&(null===(t=e.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext()),He(this,Tn,null,"f"),He(this,In,null,"f"),He(this,xn,null,"f"),this._reusedWebGLCvs=null}dispose(){this.forceLoseContext(),He(this,Rn,!0,"f")}}bn=new WeakMap,Tn=new WeakMap,In=new WeakMap,xn=new WeakMap,On=new WeakMap,Rn=new WeakMap;const Tr=(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 Ir{static get version(){return"4.2.12-dev-20250709132053"}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 o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(We.OS))return Ir.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(We.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 o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(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)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(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(!Ye(this,Wn,"f"))return"closed";if("pending"===Ye(this,Wn,"f"))return"opening";if("fulfilled"===Ye(this,Wn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Ir.isStorageAvailable("localStorage")?He(this,jn,!0,"f"):(He(this,jn,!1,"f"),console.warn("Local storage is unavailable")):He(this,jn,!1,"f")}get ifSaveLastUsedCamera(){return Ye(this,jn,"f")}get isVideoPlaying(){return!(!Ye(this,Ln,"f")||Ye(this,Ln,"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=Ye(this,Kn,"f"))||void 0===e||e.removeEventListener("click",Ye(this,qn,"f")),null===(i=Ye(this,Kn,"f"))||void 0===i||i.removeEventListener("touchend",Ye(this,qn,"f")),null===(n=Ye(this,Kn,"f"))||void 0===n||n.removeEventListener("touchmove",Ye(this,zn,"f")),He(this,Kn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(We.OS)?(t.addEventListener("touchend",Ye(this,qn,"f")),t.addEventListener("touchmove",Ye(this,zn,"f"))):t.addEventListener("click",Ye(this,qn,"f")))}get tapFocusEventBoundEl(){return Ye(this,Kn,"f")}get disposed(){return Ye(this,rr,"f")}constructor(t){var e,i;Dn.add(this),Ln.set(this,null),Mn.set(this,void 0),this._zoomPreSetting=null,Fn.set(this,()=>{"opened"===this.state&&Ye(this,Qn,"f").fire("resumed",null,{target:this,async:!1})}),Pn.set(this,()=>{Ye(this,Qn,"f").fire("paused",null,{target:this,async:!1})}),kn.set(this,void 0),Nn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Bn.set(this,void 0),jn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,Un.set(this,void 0),Vn.set(this,!0),Gn.set(this,void 0),Wn.set(this,void 0),Yn.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},Hn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Ye(this,Ln,"f")).objectFit,s=this.getResolution(),o=Ye(this,Ln,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Ye(this,Ln,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},Xn.set(this,!1),zn.set(this,()=>{He(this,Xn,!0,"f")}),qn.set(this,async t=>{var e;if(Ye(this,Xn,"f"))return void He(this,Xn,!1,"f");if(!Ye(this,Hn,"f"))return;if(!this.isVideoPlaying)return;if(!Ye(this,Mn,"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 o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Ir._onLog&&(c=Date.now());try{await Ye(this,Dn,"m",gr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Ir._onLog)throw Ir._onLog(t),t}Ir._onLog&&Ir._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Ir._onLog&&Ir._onLog("Back to continuous focus."),null===(t=Ye(this,Mn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),Ye(this,Qn,"f").fire("tapfocus",null,{target:this,async:!1})}),Kn.set(this,null),Zn.set(this,1),Jn.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Ye(this,Ln,"f"))return;const t=Ye(this,Zn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Ye(this,Ln,"f").style.transform="";else{const e=window.getComputedStyle(Ye(this,Ln,"f")).objectFit,i=Ye(this,Ln,"f").videoWidth,n=Ye(this,Ln,"f").videoHeight,{width:r,height:s}=Ye(this,Ln,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=o<a?r/(i/t):s/(n/t):"cover"===e&&(h=a>o?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-Ye(this,Jn,"f").x),c=h*(1-1/t)*(n/2-Ye(this,Jn,"f").y);Ye(this,Ln,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},$n.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===ni.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.data[t/4],e[t+1]=this.data[t/4],e[t+2]=this.data[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.data.buffer);const i=new ImageData(e,this.width,this.height);return t.getContext("2d").putImageData(i,0,0),t}),Qn.set(this,void 0),tr.set(this,["before:open","opened","before:close","closed","before:camera:change","camera:changed","before:resolution:change","resolution:changed","played","paused","resumed","tapfocus"]),this.detectedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],er.set(this,new Map),ir.set(this,!1),nr.set(this,async()=>{var t,e;if("visible"===document.visibilityState){if(Ir._onLog&&Ir._onLog("document visible. video paused: "+(null===(t=Ye(this,Ln,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Ir._onLog&&Ir._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Ir._onLog&&Ir._onLog("document visible. 1st resume video failed, try open instead.")}e||await Ye(this,Dn,"m",lr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Ir._onLog&&Ir._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Ir._onLog&&Ir._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Ye(this,Dn,"m",lr).call(this)}}}else"hidden"===document.visibilityState&&(Ir._onLog&&Ir._onLog("document hidden. video paused: "+(null===(e=Ye(this,Ln,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),rr.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(()=>{Ir.onWarning&&Ir.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),He(this,Qn,new Ni,"f"),this.imageDataGetter=new br,document.addEventListener("visibilitychange",Ye(this,nr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Ye(this,Fn,"f")),t.addEventListener("pause",Ye(this,Pn,"f")),He(this,Ln,t,"f")}getVideoEl(){return Ye(this,Ln,"f")}releaseVideoEl(){var t,e;null===(t=Ye(this,Ln,"f"))||void 0===t||t.removeEventListener("play",Ye(this,Fn,"f")),null===(e=Ye(this,Ln,"f"))||void 0===e||e.removeEventListener("pause",Ye(this,Pn,"f")),He(this,Ln,null,"f")}isVideoLoaded(){return!!Ye(this,Ln,"f")&&4==Ye(this,Ln,"f").readyState}async open(){if(Ye(this,Gn,"f")&&!Ye(this,Vn,"f")){if("pending"===Ye(this,Wn,"f"))return Ye(this,Gn,"f");if("fulfilled"===Ye(this,Wn,"f"))return}Ye(this,Qn,"f").fire("before:open",null,{target:this}),await Ye(this,Dn,"m",lr).call(this),Ye(this,Qn,"f").fire("played",null,{target:this,async:!1}),Ye(this,Qn,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Ye(this,Qn,"f").fire("before:close",null,{target:this});const t=Ye(this,Gn,"f");if(Ye(this,Dn,"m",ur).call(this),t&&"pending"===Ye(this,Wn,"f")){try{await t}catch(t){}if(!1===Ye(this,Vn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}He(this,Gn,null,"f"),He(this,Wn,null,"f"),Ye(this,Qn,"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.");Ye(this,Ln,"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 Ye(this,Ln,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Ye(this,kn,"f").video&&(Ye(this,kn,"f").video={}),delete Ye(this,kn,"f").video.facingMode,Ye(this,kn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ye(this,Vn,"f"))){Ye(this,Qn,"f").fire("before:camera:change",[],{target:this,async:!1}),await Ye(this,Dn,"m",cr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ye(this,Nn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Ye(this,kn,"f").video&&(Ye(this,kn,"f").video={}),(null==t?void 0:t.resolution)&&(Ye(this,kn,"f").video.width={ideal:t.resolution.width},Ye(this,kn,"f").video.height={ideal:t.resolution.height}),delete Ye(this,kn,"f").video.deviceId,Ye(this,kn,"f").video.facingMode={exact:"user"},He(this,Bn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ye(this,Vn,"f"))){Ye(this,Qn,"f").fire("before:camera:change",[],{target:this,async:!1}),Ye(this,Dn,"m",cr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ye(this,Nn,"f")}}getCamera(){var t;if(Ye(this,Nn,"f"))return Ye(this,Nn,"f");{let e=(null===(t=Ye(this,kn,"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)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}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<n.length;t++){let e,i=n[t];for(let t of s)if(i.deviceId==t.deviceId){e=t;break}e||(e={deviceId:i.deviceId,label:i.label?i.label:"camera "+t,_checked:!1}),e.deviceId&&r.push(e)}return this._arrCameras=r,Ir._onLog&&Ir._onLog(JSON.stringify(this._arrCameras)),r}async getCameras(){var t,e;if(!(null===(e=null===(t=null===window||void 0===window?void 0:window.navigator)||void 0===t?void 0:t.mediaDevices)||void 0===e?void 0:e.enumerateDevices))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");const i=(await navigator.mediaDevices.enumerateDevices()).filter(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 Ye(this,kn,"f").video&&(Ye(this,kn,"f").video={}),i?(Ye(this,kn,"f").video.width={exact:t},Ye(this,kn,"f").video.height={exact:e}):(Ye(this,kn,"f").video.width={ideal:t},Ye(this,kn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Ye(this,Vn,"f"))return null;Ye(this,Qn,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Ye(this,Dn,"m",cr).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&&Ye(this,Ln,"f"))return{width:Ye(this,Ln,"f").videoWidth,height:Ye(this,Ln,"f").videoHeight};if(Ye(this,Mn,"f")){const t=Ye(this,Mn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Ye(this,Ln,"f").videoWidth,height:Ye(this,Ln,"f").videoHeight};{const t={width:0,height:0};let e=Ye(this,kn,"f").video.width||0,i=Ye(this,kn,"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,o,a,h,l,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=Ye(this,er,"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=Ye(this,Nn,"f"))||void 0===u?void 0:u.deviceId;let e=Ye(this,er,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Ye(this,er,"f").set(d,e),He(this,Yn,!0,"f");try{for(let t of this.detectedResolutions){await Ye(this,Mn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Ye(this,Dn,"m",or).call(this);const i=Ye(this,Mn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Ye(this,Dn,"m",ur).call(this),He(this,Yn,!1,"f"),t}try{await Ye(this,Dn,"m",lr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{He(this,Yn,!1,"f")}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 o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=Ye(this,kn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Ye(this,kn,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Ye(this,kn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Ye(this,er,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Ye(this,er,"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'.");He(this,kn,JSON.parse(JSON.stringify(t)),"f"),He(this,Bn,null,"f"),e&&await Ye(this,Dn,"m",cr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Ye(this,kn,"f")))}resetMediaStreamConstraints(){He(this,kn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Ye(this,Mn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ye(this,Mn,"f").getCapabilities?Ye(this,Mn,"f").getCapabilities():{}}getCameraSettings(){if(!Ye(this,Mn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ye(this,Mn,"f").getSettings()}async turnOnTorch(){if(!Ye(this,Mn,"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 Ye(this,Mn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Ye(this,Mn,"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 Ye(this,Mn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ye(this,Mn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=Tr(t,n.min,n.step,n.max)),await Ye(this,Mn,"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(!Ye(this,Mn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=Tr(t,n.min,n.step,n.max)),await Ye(this,Mn,"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(!Ye(this,Mn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max));const r=this.getResolution();return await Ye(this,Mn,"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(!Ye(this,Mn,"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&&(i<r.min?i=r.min:i>r.max&&(i=r.max),i=Tr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Ye(this,Mn,"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 Ye(this,Dn,"m",gr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Ye(this,Mn,"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}enableTapToFocus(){He(this,Hn,!0,"f")}disableTapToFocus(){He(this,Hn,!1,"f")}isTapToFocusEnabled(){return Ye(this,Hn,"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){t.centerPoint?Ye(this,Dn,"m",mr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Ye(this,Dn,"m",pr).call(this,Ye(this,Jn,"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)}}else this._zoomPreSetting=t}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*Ye(this,Zn,"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(!Ye(this,Mn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=Tr(t,n.min,n.step,n.max)),await Ye(this,Mn,"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&&Ye(this,Dn,"m",mr).call(this,e),He(this,Zn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Ye(this,Zn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();He(this,Jn,{x:t.width/2,y:t.height/2},"f")}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(Ye(this,Yn,"f"))return null;const e=Date.now();Ir._onLog&&Ir._onLog("getFrameData() START: "+e);const i=Ye(this,Ln,"f").videoWidth,n=Ye(this,Ln,"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=ni.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Ye(this,Zn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Ye(this,Jn,"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.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(Ye(this,Ln,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Ir._onLog&&Ir._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Ye(this,$n,"f")}}on(t,e){if(!Ye(this,tr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Ye(this,Qn,"f").on(t,e)}off(t,e){Ye(this,Qn,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Ye(this,Qn,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Ye(this,nr,"f")),He(this,rr,!0,"f")}}var xr,Or,Rr,Ar,Dr,Lr,Mr,Fr,Pr,kr,Nr,Br,jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs;Ln=new WeakMap,Mn=new WeakMap,Fn=new WeakMap,Pn=new WeakMap,kn=new WeakMap,Nn=new WeakMap,Bn=new WeakMap,jn=new WeakMap,Un=new WeakMap,Vn=new WeakMap,Gn=new WeakMap,Wn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,Dn=new WeakSet,sr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Ye(this,Bn,"f"))delete t.video.facingMode,t.video.deviceId={exact:Ye(this,Bn,"f")};else if(this.ifSaveLastUsedCamera&&Ir.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(We.OS)?(await this._getCameras(!1),Ye(this,Dn,"m",or).call(this),e=Ir.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(We.OS)||(await this._getCameras(!1),Ye(this,Dn,"m",or).call(this),e=Ir.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},or=function(){if(Ye(this,Vn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},ar=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{Ir._onLog&&Ir._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)),Ye(this,Dn,"m",or).call(this));try{Ir._onLog&&Ir._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Ye(this,Dn,"m",or).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Ir._onLog&&Ir._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)){const t=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let e of t){const t={video:{deviceId:{ideal:e.deviceId},facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}}};if(await r(t),n)break}}if(!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}},hr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),He(this,Mn,null,"f")},lr=async function(){He(this,Vn,!1,"f");const t=He(this,Un,Symbol(),"f");if(Ye(this,Gn,"f")&&"pending"===Ye(this,Wn,"f")){try{await Ye(this,Gn,"f")}catch(t){}Ye(this,Dn,"m",or).call(this)}if(t!==Ye(this,Un,"f"))return;const e=He(this,Gn,(async()=>{He(this,Wn,"pending","f");try{if(this.videoSrc){if(!Ye(this,Ln,"f"))throw new Error("'videoEl' should be set.");await Ir.playVideo(Ye(this,Ln,"f"),this.videoSrc,this.cameraOpenTimeout),Ye(this,Dn,"m",or).call(this)}else{let t=await Ye(this,Dn,"m",sr).call(this);Ye(this,Dn,"m",hr).call(this);let e=await Ye(this,Dn,"m",ar).call(this,t);await this._getCameras(!1),Ye(this,Dn,"m",or).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=Ye(this,kn,"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),!(Ye(this,Bn,"f")||this.ifSaveLastUsedCamera&&Ir.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Ir.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 Ye(this,Dn,"m",ar).call(this,t),Ye(this,Dn,"m",or).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(He(this,Bn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Ir.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Ye(this,Bn,"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))))),Ye(this,Ln,"f")&&(await Ir.playVideo(Ye(this,Ln,"f"),e,this.cameraOpenTimeout),Ye(this,Dn,"m",or).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&He(this,Mn,s[0],"f"),He(this,Nn,r,"f")}}catch(t){throw Ye(this,Dn,"m",ur).call(this),He(this,Wn,null,"f"),t}He(this,Wn,"fulfilled","f")})(),"f");return e},cr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Ye(this,Nn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Ye(this,Dn,"m",lr).call(this);const n=this.getResolution();e&&e!==Ye(this,Nn,"f").deviceId&&Ye(this,Qn,"f").fire("camera:changed",[Ye(this,Nn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Ye(this,Qn,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Ye(this,Qn,"f").fire("played",null,{target:this,async:!1})},ur=function(){Ye(this,Dn,"m",hr).call(this),He(this,Nn,null,"f"),Ye(this,Ln,"f")&&(Ye(this,Ln,"f").srcObject=null,this.videoSrc&&(Ye(this,Ln,"f").pause(),Ye(this,Ln,"f").currentTime=0)),He(this,Vn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},dr=async function t(e,i){const n=t=>{if(!Ye(this,Mn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Ye(this,Mn,"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=Tr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Ye(this,Mn,"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,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;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(Ye(this,Ln,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:ni.RGBA,bufferContainer:d}))return Ye(this,Dn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;t<e;++t){let e=f[t]-f[t+8];++t;let i=f[t]-f[t+8];++t;let n=f[t]-f[t+8];++t,g+=e*e+i*i+n*n}return-g},fr=async function t(e,i,n,r,s,o,a){let h;if(i=Tr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Tr(r,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o?o=Tr(o,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max):(o=Tr(Math.sqrt((i||this._focusParameters.fds.step)*(r||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Ye(this,Dn,"m",dr).call(this,e,o)),a<=n&&a<=s?h=3:n<s&&n<a?h=1:s<n&&s<a&&(h=2),(r-i)/2<=this._focusParameters.fds.step)return 3===h||(1===h?await Ye(this,Mn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}):2===h&&await Ye(this,Mn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:r}]})),!0;if(1===h)return await Ye(this,Dn,"m",t).call(this,e,i,n,o,a);if(2===h)return await Ye(this,Dn,"m",t).call(this,e,o,a,r,s);if(3!==h)return n=await Ye(this,Dn,"m",dr).call(this,e,i),s=await Ye(this,Dn,"m",dr).call(this,e,r),await Ye(this,Dn,"m",t).call(this,e,i,n,r,s);let l=Tr(Math.sqrt((i||this._focusParameters.fds.step)*(o||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),c=Tr(Math.sqrt((r||this._focusParameters.fds.step)*(o||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max);if(Math.abs(1/this._focusParameters.oldDistance-1/l)<=Math.abs(1/this._focusParameters.oldDistance-1/c)){let h=await Ye(this,Dn,"m",dr).call(this,e,l);if(h<a)return await Ye(this,Dn,"m",t).call(this,e,i,n,o,a,l,h);if(h==a)return await Ye(this,Dn,"m",t).call(this,e,l,h,o,a);let u=await Ye(this,Dn,"m",dr).call(this,e,c);if(h>a&&a<u)return await Ye(this,Dn,"m",t).call(this,e,l,h,c,u,o,a);if(a==u)return await Ye(this,Dn,"m",t).call(this,e,o,a,c,u);if(a>u)return await Ye(this,Dn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await Ye(this,Dn,"m",dr).call(this,e,c);if(a>h)return await Ye(this,Dn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await Ye(this,Dn,"m",t).call(this,e,o,a,c,h);let u=await Ye(this,Dn,"m",dr).call(this,e,l);if(u>a&&a<h)return await Ye(this,Dn,"m",t).call(this,e,l,u,c,h,o,a);if(u==a)return await Ye(this,Dn,"m",t).call(this,e,l,u,o,a);if(u<a)return await Ye(this,Dn,"m",t).call(this,e,i,n,o,a,l,u)}return!1},gr=async function(t,e,i,n,r){var s;if(1==this._focusParameters.isDoingFocus)return!1;if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'centerPoint'.");if(!e||"string"!=typeof e)throw new Error("Invalid 'width'.");if(!i||"string"!=typeof i)throw new Error("Invalid 'height'.");const o=this.getResolution();let a=0,h=0;if(t.x.endsWith("px"))a=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid 'centerPoint'.");a=parseFloat(t.x)/100*o.width}if(t.y.endsWith("px"))h=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid 'centerPoint'.");h=parseFloat(t.y)/100*o.height}if(isNaN(a)||isNaN(h)||a<0||a>o.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<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*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Ye(this,Zn,"f")){const t=Ye(this,Zn,"f"),e=Ye(this,Jn,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/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:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||e<this._focusParameters.fds.min)&&(e=this._focusParameters.fds.min),(null==i||i>this._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Tr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Tr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Tr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Ye(this,Dn,"m",dr).call(this,t,s),a=await Ye(this,Dn,"m",dr).call(this,t,r),h=await Ye(this,Dn,"m",dr).call(this,t,n);if(a>h&&h<o){const e=await Ye(this,Dn,"m",fr).call(this,t,r,a,s,o,n,h);return this._focusParameters.isDoingFocus=0,e}if(a<h&&a<o){let i=await Ye(this,Dn,"m",dr).call(this,t,e);const s=await Ye(this,Dn,"m",fr).call(this,t,e,i,n,h,r,a);return this._focusParameters.isDoingFocus=0,s}if(h>o&&a>o){let e=await Ye(this,Dn,"m",dr).call(this,t,i);const r=await Ye(this,Dn,"m",fr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&h<o){const e=await Ye(this,Dn,"m",fr).call(this,t,r,a,n,h);return this._focusParameters.isDoingFocus=0,e}if(h==o&&a>h){const e=await Ye(this,Dn,"m",fr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},mr=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.");He(this,Jn,{x:i,y:n},"f")},pr=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},Ir.browserInfo=We,Ir.onWarning=null===(An=null===window||void 0===window?void 0:window.console)||void 0===An?void 0:An.warn;class ls{constructor(t){xr.add(this),Or.set(this,void 0),Rr.set(this,0),Ar.set(this,void 0),Dr.set(this,0),Lr.set(this,!1),He(this,Or,t,"f")}startCharging(){Ye(this,Lr,"f")||(ls._onLog&&ls._onLog("start charging."),Ye(this,xr,"m",Fr).call(this),He(this,Lr,!0,"f"))}stopCharging(){Ye(this,Ar,"f")&&clearTimeout(Ye(this,Ar,"f")),Ye(this,Lr,"f")&&(ls._onLog&&ls._onLog("stop charging."),He(this,Rr,Date.now()-Ye(this,Dr,"f"),"f"),He(this,Lr,!1,"f"))}}Or=new WeakMap,Rr=new WeakMap,Ar=new WeakMap,Dr=new WeakMap,Lr=new WeakMap,xr=new WeakSet,Mr=function(){Bt.cfd(1),ls._onLog&&ls._onLog("charge 1.")},Fr=function t(){0==Ye(this,Rr,"f")&&Ye(this,xr,"m",Mr).call(this),He(this,Dr,Date.now(),"f"),Ye(this,Ar,"f")&&clearTimeout(Ye(this,Ar,"f")),He(this,Ar,setTimeout(()=>{He(this,Rr,0,"f"),Ye(this,xr,"m",t).call(this)},Ye(this,Or,"f")-Ye(this,Rr,"f")),"f")};class cs{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ye(this,Pr,"f",Br)<100)){if(He(this,Pr,e,"f",Br),Ye(this,Pr,"f",kr).size&&(t=Ye(this,Pr,"f",kr).values().next().value,this.beepSoundSource==t.src?(Ye(this,Pr,"f",kr).delete(t),t.play()):t=null),!t)if(Ye(this,Pr,"f",Nr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{Ye(this,Pr,"f",Nr).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ye(this,Pr,"f",Nr).delete(t),Ye(this,Pr,"f",kr).add(t)})}else Ye(this,Pr,"f",jr)||(He(this,Pr,!0,"f",jr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ye(this,Pr,"f",Nr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(cs.vibrateDuration)}}}Pr=cs,kr={value:new Set},Nr={value:new Set},Br={value:0},jr={value:!1},cs.allowBeep=!0,cs.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",cs.allowVibrate=!0,cs.vibrateDuration=300;const us=new Map([[ni.GREY,v.IPF_GRAYSCALED],[ni.RGBA,v.IPF_ABGR_8888]]),ds="function"==typeof BigInt?t=>BigInt(t):t=>t,fs=(ds("0x00"),ds("0xFFFFFFFFFFFFFFFF"),ds("0xFE3BFFFF"),ds("0x003007FF")),gs=(ds("0x0003F800"),ds("0x1"),ds("0x2"),ds("0x4"),ds("0x8"),ds("0x10"),ds("0x20"),ds("0x40"),ds("0x80"),ds("0x100"),ds("0x200"),ds("0x400"),ds("0x800"),ds("0x1000"),ds("0x2000"),ds("0x4000"),ds("0x8000"),ds("0x10000"),ds("0x20000"),ds("0x00040000"),ds("0x01000000"),ds("0x02000000"),ds("0x04000000")),ms=ds("0x08000000");ds("0x10000000"),ds("0x20000000"),ds("0x40000000"),ds("0x00080000"),ds("0x80000000"),ds("0x100000"),ds("0x200000"),ds("0x400000"),ds("0x800000"),ds("0x1000000000"),ds("0x3F0000000000000"),ds("0x100000000"),ds("0x10000000000000"),ds("0x20000000000000"),ds("0x40000000000000"),ds("0x80000000000000"),ds("0x100000000000000"),ds("0x200000000000000"),ds("0x200000000"),ds("0x400000000"),ds("0x800000000"),ds("0xC00000000"),ds("0x2000000000"),ds("0x4000000000");class ps extends it{static set _onLog(t){He(ps,Vr,t,"f",Gr),Ir._onLog=t,ls._onLog=t}static get _onLog(){return Ye(ps,Vr,"f",Gr)}static async detectEnvironment(){return await(async()=>({wasm:Xe,worker:ze,getUserMedia:qe,camera:await Ke(),browser:We.browser,version:We.version,OS:We.OS}))()}static async testCameraAccess(){const t=await Ir.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 Sr))throw new TypeError("Invalid view.");if(!ps._isRTU&&(null===(e=Pt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=Pt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await Bt.loadWasm(),await Pt.license.dynamsoft()}const n=new ps(t);return ps.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{ps.onWarning&&ps.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(()=>{ps.onWarning&&ps.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 isEnableMirroring(){return this._isEnableMirroring}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.");He(this,Xr,t,"f")}get singleFrameMode(){return Ye(this,Xr,"f")}get _isFetchingStarted(){return Ye(this,$r,"f")}get disposed(){return Ye(this,ns,"f")}constructor(t){if(super(),Ur.add(this),Wr.set(this,"closed"),Yr.set(this,void 0),Hr.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,Xr.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()},zr.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},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;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 a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?ni.GREY:ni.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===ni.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:us.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:dt.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:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:Ye(this,qr,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Fi.convert(Ye(this,Zr,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ye(this,zr,"f").call(this,t,t.width,t.height,e);Ye(this,Yr,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},qr.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===v.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.bytes[t/4],e[t+1]=this.bytes[t/4],e[t+2]=this.bytes[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.bytes.buffer);return t.getContext("2d").putImageData(new ImageData(e,this.width,this.height),0,0),t}),Kr.set(this,void 0),Zr.set(this,void 0),Jr.set(this,v.IPF_ABGR_8888),$r.set(this,!1),this._imageId=-1,Qr.set(this,void 0),this.fetchInterval=0,ts.set(this,{enhancedFocus:!1,autoZoom:!1,tapToFocus:!1}),es.set(this,{minValue:1,maxValue:999,autoFocusFrameArray:[],autoFocusFrameLimit:[5,3],autoZoomDetectionArea:.5,autoZoomTargetBorder:.9,autoZoomIdealArea:[0,.05],autoZoomInFrameArray:[],autoZoomInFrameLimit:[5,3],autoZoomInMaxTimes:5,autoZoomInMinStep:Math.pow(10,.2),autoZoomInIdealModuleSize:6,autoZoomOutFrameCount:0,autoZoomOutFrameLimit:3,autoZoomOutStepRate:1/3,autoZoomOutStepRate_2:.05,autoZoomOutMinStep:2,frameArrayInIdealZoom:[],frameLimitInIdealZoom:[5,3]}),is.set(this,void 0),ns.set(this,!1),this.isCameraEnhancer=!0,this._taskid4AutoTorch=null,this._delay4AutoTorch=250,this.grayThreshold4AutoTorch=20,this.maxDarkCount4AutoTroch=3,t&&!(t instanceof Sr))throw new TypeError("Invalid view.");He(this,Yr,new Ni,"f"),this.cameraManager=new Ir,this._imageDataGetter=this.cameraManager.imageDataGetter,this.cameraManager.updateVideoElWhenSoftwareScaled=()=>{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(We.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",()=>{Ye(this,is,"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",()=>{Ye(this,is,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{Ye(this,ts,"f").tapToFocus&&Ye(this,is,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(Ye(this,Ur,"m",rs).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;ps._onLog&&(ps._onLog("intermediateResultUnits:"),ps._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===pt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===pt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ps._onLog&&(ps._onLog("hasLocalizedBarcodes:"),ps._onLog(h)),Ye(this,ts,"f").autoZoom||Ye(this,ts,"f").enhancedFocus)if(a)Ye(this,es,"f").autoZoomInFrameArray.length=0,Ye(this,es,"f").autoZoomOutFrameCount=0,Ye(this,es,"f").frameArrayInIdealZoom.length=0,Ye(this,es,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ye(this,ts,"f").autoZoom&&Ye(this,is,"f").startCharging()},a=async t=>{await this.setFocus(t),Ye(this,ts,"f").enhancedFocus&&Ye(this,is,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Ye(this,es,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ye(this,es,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Ye(this,es,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ye(this,es,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}ps._onLog&&(ps._onLog("detectionArea:"),ps._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;s<r;s++){const o=t[s],a=t[(s+1)%r];if(Bi(o,a,{x:e,y:i}))return!0;ji(o.y-i)>0!=ji(a.y-i)>0&&ji(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Ui([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Ui([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Ui([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Ui([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 o)if(e.unitType===pt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Sr._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(ps._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=_r.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===pt.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new bi({points:i},e);t.addDrawingItems([r])}}}if(ps._onLog&&(ps._onLog("intersectedResults:"),ps._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==gs||t.possibleFormats==ms);if(t.length||(t=s.filter(t=>t.possibleFormats==fs),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)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n<t.length;n++){const r=e(t[n]);(t[n].confidence>1.1*a.confidence||t[n].confidence>.9*a.confidence&&r<i)&&(a=t[n],i=r)}}}if(ps._onLog&&(ps._onLog("highPriorityResult:"),ps._onLog(a)),a){const r=a.location.points;t=Math.min(r[0].x,r[1].x,r[2].x,r[3].x),e=Math.max(r[0].x,r[1].x,r[2].x,r[3].x),i=Math.min(r[0].y,r[1].y,r[2].y,r[3].y),n=Math.max(r[0].y,r[1].y,r[2].y,r[3].y),m={points:[{x:t,y:i},{x:e,y:i},{x:e,y:n},{x:t,y:n}],result:a}}}if(ps._onLog&&(ps._onLog("boundingRect:"),ps._onLog(m)),!m)return;if(ps._debug&&this.cameraView&&(null==m?void 0:m.points)){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99)),e=this.__styleId1||(this.__styleId1=_r.createDrawingStyle({strokeStyle:"blue"})),i=new bi({points:m.points},e);t.addDrawingItems([i])}if(Ye(this,es,"f").autoZoomOutFrameCount=0,Ye(this,ts,"f").autoZoom){const i=Ye(this,es,"f").autoZoomIdealArea[1];let n=(1-Ye(this,es,"f").autoZoomTargetBorder)/2;const r=m.points[0].x/u,s=(u-m.points[2].x)/u,o=m.points[0].y/d,h=(d-m.points[2].y)/d;if(r>i&&s>i&&o>i&&h>i&&m.result.moduleSize<Ye(this,es,"f").autoZoomInIdealModuleSize){if(Ye(this,es,"f").autoZoomInFrameArray.push(!0),Ye(this,es,"f").autoZoomInFrameArray.splice(0,Ye(this,es,"f").autoZoomInFrameArray.length-Ye(this,es,"f").autoZoomInFrameLimit[0]),Ye(this,es,"f").frameArrayInIdealZoom.length=0,Ye(this,ts,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{}),Ye(this,es,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=Ye(this,es,"f").autoZoomInFrameLimit[1]){Ye(this,es,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,Ye(this,es,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ye(this,es,"f").autoZoomInMaxTimes),Ye(this,es,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ye(this,es,"f").minValue,u),u=Math.min(Ye(this,es,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ye(this,es,"f").autoZoomInFrameArray.length=0,Ye(this,es,"f").frameArrayInIdealZoom.push(!0),Ye(this,es,"f").frameArrayInIdealZoom.splice(0,Ye(this,es,"f").frameArrayInIdealZoom.length-Ye(this,es,"f").frameLimitInIdealZoom[0]),Ye(this,es,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=Ye(this,es,"f").frameLimitInIdealZoom[1]&&(Ye(this,es,"f").frameArrayInIdealZoom.length=0,Ye(this,ts,"f").enhancedFocus)){const e=m.points;try{await a({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(!Ye(this,ts,"f").autoZoom&&Ye(this,ts,"f").enhancedFocus&&(Ye(this,es,"f").autoFocusFrameArray.push(!0),Ye(this,es,"f").autoFocusFrameArray.splice(0,Ye(this,es,"f").autoFocusFrameArray.length-Ye(this,es,"f").autoFocusFrameLimit[0]),Ye(this,es,"f").autoFocusFrameArray.filter(t=>!0===t).length>=Ye(this,es,"f").autoFocusFrameLimit[1])){Ye(this,es,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({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(Ye(this,ts,"f").autoZoom){if(Ye(this,es,"f").autoZoomInFrameArray.push(!1),Ye(this,es,"f").autoZoomInFrameArray.splice(0,Ye(this,es,"f").autoZoomInFrameArray.length-Ye(this,es,"f").autoZoomInFrameLimit[0]),Ye(this,es,"f").autoZoomOutFrameCount++,Ye(this,es,"f").frameArrayInIdealZoom.push(!1),Ye(this,es,"f").frameArrayInIdealZoom.splice(0,Ye(this,es,"f").frameArrayInIdealZoom.length-Ye(this,es,"f").frameLimitInIdealZoom[0]),Ye(this,es,"f").autoZoomOutFrameCount>=Ye(this,es,"f").autoZoomOutFrameLimit){Ye(this,es,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Ye(this,es,"f").autoZoomOutStepRate,Ye(this,es,"f").autoZoomOutMinStep);n=Math.max(Ye(this,es,"f").minValue,n),n=Math.min(Ye(this,es,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ye(this,ts,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!Ye(this,ts,"f").autoZoom&&Ye(this,ts,"f").enhancedFocus&&(Ye(this,es,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},He(this,is,new ls(1e4),"f")}setCameraView(t){if(!(t instanceof Sr))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),Ye(this,Ur,"m",rs).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;Ye(this,Ur,"m",rs).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 Ye(this,Ur,"m",rs).call(this)?Ye(this,Wr,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,Ye(this,Ur,"m",rs).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(Ye(this,Ur,"m",rs).call(this));else{try{await this.cameraManager.open(),He(this,Hr,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=cs.allowBeep?"":"none"),a&&(a.style.display=cs.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=cs.allowVibrate?"":"none"),l&&(l.style.display=cs.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const C=()=>{cs.allowBeep=!cs.allowBeep,o&&(o.style.display=cs.allowBeep?"":"none"),a&&(a.style.display=cs.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",C);const E=()=>{cs.allowVibrate=!cs.allowVibrate,h&&(h.style.display=cs.allowVibrate?"":"none"),l&&(l.style.display=cs.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",E);const S=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&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);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(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=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=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==We?void 0:We.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",C);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",E);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return He(this,Wr,"open","f"),e&&(e._innerComponent.style.display="",Ye(this,Ur,"m",rs).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),Ye(this,Yr,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}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(),Ye(this,Ur,"m",rs).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())}He(this,Wr,"closed","f"),Ye(this,is,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ye(this,Ur,"m",rs).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ye(this,Yr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ye(this,Ur,"m",rs).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ye(this,Ur,"m",rs).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ye(this,Ur,"m",rs).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.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})),this.toggleMirroring(this._isEnableMirroring),{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())?Ye(this,Yr,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ye(this,Yr,"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(Ye(this,Ur,"m",rs).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(Ye(this,Ur,"m",rs).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){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t<this._delay4AutoTorch))return;clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null}this._delay4AutoTorch=t;let n=!1,r=0,s=0;const o=async()=>{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(v.IPF_GRAYSCALED===o.format){for(let t=0;t<o.bytes.length;++t)a+=o.bytes[t];a/=o.bytes.length}else{if(v.IPF_ABGR_8888!==o.format)return;for(let t=0;t<o.bytes.length;t+=4)a+=o.bytes[t],a+=o.bytes[t+1],a+=o.bytes[t+2];a/=o.bytes.length/4*3}if(a<this.grayThreshold4AutoTorch){if(++r>=this.maxDarkCount4AutoTroch){null===(t=ps._onLog)||void 0===t||t.call(ps,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ye(this,Ur,"m",rs).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(Ye(this,Ur,"m",rs).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(Ye(this,Ur,"m",rs).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(Ye(this,Ur,"m",rs).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(Ye(this,Ur,"m",rs).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(Ye(this,Ur,"m",rs).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){Ye(this,es,"f").minValue=t.min,Ye(this,es,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ye(this,es,"f").minValue,max:Ye(this,es,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=Pt.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!==Bt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ii.EF_ENHANCED_FOCUS&&(Ye(this,ts,"f").enhancedFocus=!0),t&ii.EF_AUTO_ZOOM&&(Ye(this,ts,"f").autoZoom=!0),t&ii.EF_TAP_TO_FOCUS&&(Ye(this,ts,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ii.EF_ENHANCED_FOCUS&&(Ye(this,ts,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&ii.EF_AUTO_ZOOM&&(Ye(this,ts,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&ii.EF_TAP_TO_FOCUS&&(Ye(this,ts,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ye(this,Ur,"m",os).call(this)&&Ye(this,Ur,"m",ss).call(this)||Ye(this,is,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!R(t)&&!P(t))throw TypeError("Invalid 'region'.");He(this,Zr,t?JSON.parse(JSON.stringify(t)):null,"f"),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(Ye(this,Zr,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");He(this,Kr,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ye(this,Ur,"m",rs).call(this))}startFetching(){if(Ye(this,Ur,"m",rs).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ye(this,$r,"f")||(He(this,$r,!0,"f"),Ye(this,Ur,"m",as).call(this))}stopFetching(){Ye(this,$r,"f")&&(ps._onLog&&ps._onLog("DCE: stop fetching loop: "+Date.now()),Ye(this,Qr,"f")&&clearTimeout(Ye(this,Qr,"f")),He(this,$r,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(Ye(this,Ur,"m",rs).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 e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i;if(i=Fi.convert(Ye(this,Zr,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y);const n=this.cameraView.regionMaskLineWidth;let r;r=Ye(this,Zr,"f")&&!t?{sx:i.x+n,sy:i.y+n,sWidth:i.width-2*n,sHeight:i.height-2*n,dWidth:i.width-2*n,dHeight:i.height-2*n}:{sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};const s=Math.max(r.dWidth,r.dHeight);if(this.canvasSizeLimit&&s>this.canvasSizeLimit){const t=this.canvasSizeLimit/s;r.dWidth>r.dHeight?(r.dWidth=this.canvasSizeLimit,r.dHeight=Math.round(r.dHeight*t)):(r.dWidth=Math.round(r.dWidth*t),r.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:r,pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?ni.GREY:ni.RGBA,isEnableMirroring:this._isEnableMirroring});if(!o)return null;let a;a=o.pixelFormat===ni.GREY?o.width:4*o.width;let h=!0;return 0===r.sx&&0===r.sy&&r.sWidth===e.width&&r.sHeight===e.height&&(h=!1),{bytes:o.data,width:o.width,height:o.height,stride:a,format:us.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:dt.ITT_VIDEO_FRAME,isCropped:h,cropRegion:{left:r.sx,top:r.sy,right:r.sx+r.sWidth,bottom:r.sy+r.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:Ye(this,qr,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ye(this,$r,"f")&&(Ye(this,Qr,"f")&&clearTimeout(Ye(this,Qr,"f")),He(this,Qr,setTimeout(()=>{this.disposed||Ye(this,Ur,"m",as).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){He(this,Jr,t,"f")}getPixelFormat(){return Ye(this,Jr,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ye(this,Ur,"m",rs).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 o=Fi.convert(Ye(this,Zr,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=Ye(this,zr,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ye(this,Ur,"m",hs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ye(this,Ur,"m",hs).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Ye(this,Zr,"f"))return JSON.parse(JSON.stringify(t));if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});He(this,Hr,t||Ye(this,Hr,"f"),"f")}let e,i,n=Ye(this,Zr,"f").left||Ye(this,Zr,"f").x||0,r=Ye(this,Zr,"f").top||Ye(this,Zr,"f").y||0;if(!Ye(this,Zr,"f").isMeasuredInPercentage)return{x:t.x-(n+this.cameraView.regionMaskLineWidth+Ye(this,Hr,"f").x),y:t.y-(r+this.cameraView.regionMaskLineWidth+Ye(this,Hr,"f").y)};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(!Ye(this,Ur,"m",rs).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ye(this,Ur,"m",rs).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Ye(this,Ur,"m",rs).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else e=Ye(this,Hr,"f").width,i=Ye(this,Hr,"f").height;return{x:t.x-(Math.round(n*e/100)+this.cameraView.regionMaskLineWidth+Ye(this,Hr,"f").x),y:t.y-(Math.round(r*i/100)+this.cameraView.regionMaskLineWidth+Ye(this,Hr,"f").y)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),He(this,ns,!0,"f")}}var _s,vs,ys,ws,Cs,Es,Ss,bs;Vr=ps,Wr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,qr=new WeakMap,Kr=new WeakMap,Zr=new WeakMap,Jr=new WeakMap,$r=new WeakMap,Qr=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,ns=new WeakMap,Ur=new WeakSet,rs=function(){return"disabled"!==this.singleFrameMode},ss=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},os=function(){for(let t in Ye(this,ts,"f"))if(1==Ye(this,ts,"f")[t])return!0;return!1},as=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ye(this,$r,"f"))return Ye(this,Qr,"f")&&clearTimeout(Ye(this,Qr,"f")),void He(this,Qr,setTimeout(()=>{this.disposed||Ye(this,Ur,"m",t).call(this)},this.fetchInterval),"f");const e=()=>{var t;let e;ps._onLog&&ps._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=Ye(this,Kr,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=Ye(this,Kr,"f"))||void 0===t||t.onErrorReceived(lt.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),ps._onLog&&ps._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ye(this,Yr,"f").fire("frameAddedToBuffer",null,{async:!1})):ps._onLog&&ps._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:e()}else e();Ye(this,Qr,"f")&&clearTimeout(Ye(this,Qr,"f")),He(this,Qr,setTimeout(()=>{this.disposed||Ye(this,Ur,"m",t).call(this)},this.fetchInterval),"f")},hs=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(!Ye(this,Ur,"m",rs).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ye(this,Ur,"m",rs).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:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ye(this,Ur,"m",rs).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u<d?(_=o/h,f=i+t.x*_,g=n+t.y*_+(a-l*_)/2,m=r+t.x*_,p=s+t.y*_+(a-l*_)/2):(_=a/l,f=i+t.x*_+(o-h*_)/2,g=n+t.y*_,m=r+t.x*_+(o-h*_)/2,p=s+t.y*_);else if("cover"===c)if(u<d){_=a/l;let e=t.x*_-(h*_-o)/2;e=Math.max(e,0),e=Math.min(e,o),f=i+e,g=n+t.y*_,m=r+e,p=s+t.y*_}else{_=o/h;let e=t.y*_-(l*_-a)/2;e=Math.max(e,0),e=Math.min(e,a),f=i+t.x*_,g=n+e,m=r+t.x*_,p=s+e}return{clientX:f,clientY:g,pageX:m,pageY:p}},ps._debug=!1,ps._isRTU=!1,Gr={value:void 0},ps.browserInfo=We;class Ts{get magnifierCanvas(){return Ye(this,_s,"f")}constructor(){_s.set(this,void 0),He(this,_s,document.createElement("canvas"),"f"),Ye(this,_s,"f").style.borderRadius="50%"}update(t,e,i,n){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");const r=this.magnifierCanvas;r.width=r.height=t;let s=e.x-i/2,o=e.y-i/2,a=i,h=i,l=r.width,c=r.height,u=r.getContext("2d");for(let t of n)u.drawImage(t.image,s,o,a,h,0,0,l,c);r.style.width=r.width+"px",r.style.height=r.height+"px"}show(){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");this.magnifierCanvas.style.display="block"}hide(){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");this.magnifierCanvas.style.display="none"}}_s=new WeakMap;class Is extends Cr{static async createInstance(t){const e=new Is;return await e.setUIElement(t||Ye(e,vs,"m",bs).call(e)),e}get disposed(){return Ye(this,Ss,"f")}constructor(){super(),vs.add(this),this.containerClassName="dce-image-container",ys.set(this,void 0),ws.set(this,void 0),this.isUseMagnifier=!0,Cs.set(this,t=>{var e;if(!this.isUseMagnifier)return;if(Ye(this,ws,"f")||He(this,ws,new Ts,"f"),!Ye(this,ws,"f").magnifierCanvas)return;document.body.contains(Ye(this,ws,"f").magnifierCanvas)||(Ye(this,ws,"f").magnifierCanvas.style.position="fixed",Ye(this,ws,"f").magnifierCanvas.style.boxSizing="content-box",Ye(this,ws,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ye(this,ws,"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 Ye(this,Es,"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,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Ye(this,ws,"f").update(s,t.pointer,r,o);{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?(Ye(this,ws,"f").magnifierCanvas.style.left="auto",Ye(this,ws,"f").magnifierCanvas.style.top="0",Ye(this,ws,"f").magnifierCanvas.style.right="0"):(Ye(this,ws,"f").magnifierCanvas.style.left="0",Ye(this,ws,"f").magnifierCanvas.style.top="0",Ye(this,ws,"f").magnifierCanvas.style.right="auto")}Ye(this,ws,"f").show()}),Es.set(this,()=>{Ye(this,ws,"f")&&Ye(this,ws,"f").hide()}),Ss.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Vi(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(O(t)){He(this,ys,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===v.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t<s.length;t+=4)s[t]=n[t/4],s[t+1]=n[t/4],s[t+2]=n[t/4],s[t+3]=255}else s=new Uint8ClampedArray(n.buffer);this.setImage(s,e,i)}else if(t instanceof HTMLCanvasElement)He(this,ys,t,"f"),this.setImage(t,t.width,t.height);else{if(!(t instanceof HTMLImageElement))throw new TypeError("Invalid img.");He(this,ys,t,"f"),this.setImage(t,t.naturalWidth,t.naturalHeight)}let e;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(e)}getOriginalImage(){return Ye(this,ys,"f")}getContentDimensions(){let t,e,i;if(this._innerComponent){const n=this._innerComponent.getElement("content");t=null==n?void 0:n.width,e=null==n?void 0:n.height,i="contain"}if(!t||!e)throw new Error("Invalid content dimensions.");return{width:t,height:e,objectFit:i}}_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)||300),i||(i=(null==r?void 0:r.height)||150),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);this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),t!=vr.TIP_LAYER_ID&&s.setMode("editor");const o=this._drawingLayerManager._getFabricCanvas();return o&&(o.on("object:scaling",Ye(this,Cs,"f")),o.on("object:rotating",Ye(this,Cs,"f")),o.on("object:skewing",Ye(this,Cs,"f")),o.on("mouse:up",Ye(this,Es,"f"))),s}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,Es=new WeakMap,Ss=new WeakMap,vs=new WeakSet,bs=function(){const t=document.createElement("div");return t.className=this.containerClassName,t.style.width="100%",t.style.height="100%",t};var xs=Object.freeze({__proto__:null,CameraEnhancer:ps,CameraEnhancerModule:class{static getVersion(){return"4.2.12-dev-20250709132053"}},CameraManager:Ir,CameraView:Sr,DrawingItem:vi,DrawingStyleManager:_r,get EnumDrawingItemMediaType(){return ti},get EnumDrawingItemState(){return ei},get EnumEnhancedFeatures(){return ii},Feedback:cs,GroupDrawingItem:Ai,ImageDataGetter:br,ImageDrawingItem:class extends vi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Ye(this,pi,"f")}constructor(t,e,i,n){if(super(null,n),mi.set(this,void 0),pi.set(this,void 0),!P(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ri.Image(t,{left:e.x,top:e.y}));else{if(!O(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===v.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e<n.length;e+=4)n[e]=t.bytes[e/4],n[e+1]=t.bytes[e/4],n[e+2]=t.bytes[e/4],n[e+3]=255}else n=new Uint8ClampedArray(t.bytes.buffer);i.getContext("2d").putImageData(new ImageData(n,t.width,t.height),0,0),this._setFabricObject(new ri.Image(i,{left:e.x,top:e.y}))}}if(i){const t=e.width/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",e.width/this.get("width")),this.set("scaleY",e.height/this.get("height"));this.image=t,He(this,mi,JSON.parse(JSON.stringify(e)),"f"),He(this,pi,i,"f"),this._mediaType="image"}extendSet(t,e){if("image"===t){if(e instanceof HTMLImageElement)return this._fabricObject.setElement(e),this.image=e,!0;if(e instanceof HTMLCanvasElement){const t=new Image;return t.src=e.toDataURL(),this._fabricObject.setElement(t),this.image=e,!0}throw new Error("Unsupported value.")}}extendGet(t){if("image"===t)return this.image}updateCoordinateBaseFromImageToView(){if(this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),Ye(this,pi,"f")){const t=this.convertPropFromViewToImage(this.get("width"))/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",this.convertPropFromViewToImage(this.get("width"))/this.get("width")),this.set("scaleY",this.convertPropFromViewToImage(this.get("height"))/this.get("height"))}updateCoordinateBaseFromViewToImage(){if(this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),Ye(this,pi,"f")){const t=this.convertPropFromImageToView(this.get("width"))/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",this.convertPropFromImageToView(this.get("width"))/this.get("width")),this.set("scaleY",this.convertPropFromImageToView(this.get("height"))/this.get("height"))}setPosition(t){this.setImageRect(t)}getPosition(){return this.getImageRect()}updatePosition(){Ye(this,mi,"f")&&this.setImageRect(Ye(this,mi,"f"))}setImage(t){const e=this.getImageRect();if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this.set("image",t);else{if(!O(t))throw new TypeError("Invalid 'image'.");{const e=document.createElement("canvas");let i;if(e.width=t.width,e.height=t.height,t.format===v.IPF_GRAYSCALED){i=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e<i.length;e+=4)i[e]=t.bytes[e/4],i[e+1]=t.bytes[e/4],i[e+2]=t.bytes[e/4],i[e+3]=255}else i=new Uint8ClampedArray(t.bytes.buffer);e.getContext("2d").putImageData(new ImageData(i,t.width,t.height),0,0),this.set("image",e)}}if(Ye(this,pi,"f")){const t=e.width/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",e.width/this.get("width")),this.set("scaleY",e.height/this.get("height"))}getImage(){return this.image}setImageRect(t){if(!P(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)if(this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),Ye(this,pi,"f")){const e=this.convertPropFromViewToImage(t.width)/this.get("width");this.set("scaleX",e),this.set("scaleY",e)}else this.set("scaleX",this.convertPropFromViewToImage(t.width)/this.get("width")),this.set("scaleY",this.convertPropFromViewToImage(t.height)/this.get("height"));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");if(this.set("left",t.x),this.set("top",t.y),Ye(this,pi,"f")){const e=t.width/this.get("width");this.set("scaleX",e),this.set("scaleY",e)}else this.set("scaleX",t.width/this.get("width")),this.set("scaleY",t.height/this.get("height"))}this._drawingLayer.renderAll()}else He(this,mi,JSON.parse(JSON.stringify(t)),"f")}getImageRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ye(this,mi,"f")?JSON.parse(JSON.stringify(Ye(this,mi,"f"))):null}},ImageEditorView:Is,LineDrawingItem:class extends bi{constructor(t,e){if(super({points:[null==t?void 0:t.startPoint,null==t?void 0:t.endPoint]},e),xi.set(this,void 0),!D(t))throw new TypeError("Invalid 'line'.");He(this,xi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="line"}extendSet(t,e){if("startPoint"===t||"endPoint"===t){e="startPoint"===t?[e,this.get("endPoint")]:[this.get("startPoint"),e];const i=this._fabricObject;if(i.group){const t=i.group;i.points=e.map(e=>({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 ri.Control({positionHandler:wi,actionHandler:Si(i>0?i-1:n,Ei),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=ri.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(){Ye(this,xi,"f")&&this.setLine(Ye(this,xi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!D(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 He(this,xi,JSON.parse(JSON.stringify(t)),"f")}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 Ye(this,xi,"f")?JSON.parse(JSON.stringify(Ye(this,xi,"f"))):null}},QuadDrawingItem:Ri,RectDrawingItem:yi,TextDrawingItem:Ii});const Os="undefined"==typeof self,Rs=Os?{}:self,As="function"==typeof importScripts,Ds=(()=>{if(!As){if(!Os&&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"./"}})(),Ls=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ms=(async()=>{})().constructor;let Fs=class extends Ms{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,Ls(t)?e=t:"function"==typeof t&&(e=new Ms(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&&(Ls(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ps=" is not allowed to change after `createInstance` or `loadWasm` is called.",ks=!Os&&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"))||"",Ns=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ps);i._license=e}};!Os&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bs=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e<t.length;++e){if(!Os){let i=document.createElement("a");i.href=t[e],t[e]=i.href}t[e].endsWith("/")||(t[e]+="/")}}return t},js=(t,e)=>{e=Bs(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ps);i._licenseServer=e}},Us=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ps);i._deviceFriendlyName=e}};let Vs,Gs,Ws,Ys,Hs;"undefined"!=typeof navigator&&(Vs=navigator,Gs=Vs.userAgent,Ws=Vs.platform,Ys=Vs.mediaDevices),function(){if(!Os){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Vs.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:Ws,search:"Win"},Mac:{str:Ws},Linux:{str:Ws}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Gs,o=r.search||e,a=r.verStr||Gs,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Gs,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Gs.indexOf("Windows NT")&&(r="HarmonyOS"),Hs={browser:i,version:n,OS:r}}Os&&(Hs={browser:"ssr",version:0,OS:"ssr"})}(),Ys&&Ys.getUserMedia,"Chrome"===Hs.browser&&Hs.version>66||"Safari"===Hs.browser&&Hs.version>13||"OPR"===Hs.browser&&Hs.version>43||"Edge"===Hs.browser&&Hs.version;const Xs=()=>(Bt.loadWasm(),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,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.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(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Bs(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Rs.crypto||(s="Please upgrade your browser to support online key."),Rs.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Ps)})(qs),o=new Fs;qs._pLoad.task=o,(async()=>{try{await qs._pLoad}catch(t){}})();let a=Ot();Rt[a]=e=>{if(e.message&&qs._onAuthMessage){let t=qs._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(At&&At("init license success"),e.message&&console.warn(e.message),Bt._bSupportIRTModule=e.bSupportIRTModule,Bt._bSupportDce4Module=e.bSupportDce4Module,qs.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.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=B(Bt.engineResourcePaths),i=("DCV"===Bt._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(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.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t<s.childElementCount;++t){let e=s.children[t];e instanceof HTMLStyleElement&&(o.push(e),document.head.append(e))}let a=1==s.childElementCount?s.children[0]:s;a.remove();let h,l,c,u,d,f=[a],g=a.children;for(let t of g)f.push(t);for(let t=0;t<f.length;++t)for(let e of f[t].children)f.push(e);for(let t of f)if(!h&&t.classList.contains("dls-license-mask"))h=t,t.addEventListener("click",e=>{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)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 o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:qs._bNeverShowDialog,engineResourcePath:i,_onLog:At},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await bt("core"),It.postMessage({type:"license_dynamsoft",body:{v:"4.0.30-dev-20250708175739",brtk:!!t,bptk:1===t,l:e,os:Hs,fn:qs.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),qs.bCallInitLicense=!0,await o}));let zs;Pt.license={},Pt.license.dynamsoft=Xs,Pt.license.getAR=async()=>{{let t=St.dynamsoft_inited;t&&t.isRejected&&await t}return It?new Promise((t,e)=>{let i=Ot();Rt[i]=async i=>{if(i.success){delete i.success;{let t=qs.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)}},It.postMessage({type:"license_getAR",id:i})}):null};let qs=class t{static setLicenseServer(e){js(t,e)}static get license(){return this._license}static set license(e){Ns(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){js(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Us(t,e)}static initLicense(e,i){if(Ns(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Xs()}static setDeviceFriendlyName(e){Us(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await Tt("dynamsoft_uuid",async()=>{await Bt.loadWasm();let t=new Fs,e=Ot();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)}},It.postMessage({type:"license_getDeviceUUID",id:e}),zs=await t}),zs))()}};qs._pLoad=new Fs,qs.bPassValidation=!1,qs.bCallInitLicense=!1,qs._license=ks,qs._licenseServer=[],qs._deviceFriendlyName="",Bt.engineResourcePaths.license={version:"4.0.30-dev-20250708175739",path:Ds,isInternal:!0},kt.license={wasm:!0,js:!0},Pt.license.LicenseManager=qs;const Ks="2.0.0";"string"!=typeof Bt.engineResourcePaths.std&&N(Bt.engineResourcePaths.std.version,Ks)<0&&(Bt.engineResourcePaths.std={version:Ks,path:(t=>{if(null==t&&(t="./"),Os||As);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Ds+`../../dynamsoft-capture-vision-std@${Ks}/dist/`),isInternal:!0});var Zs=Object.freeze({__proto__:null,LicenseManager:qs,LicenseModule:class{static getVersion(){return`4.0.30-dev-20250708175739(Worker: ${Ft.license&&Ft.license.worker||"Not Loaded"}, Wasm: ${Ft.license&&Ft.license.wasm||"Not Loaded"})`}}});const Js=()=>window.matchMedia("(orientation: landscape)").matches,$s=t=>Object.prototype.toString.call(t).slice(8,-1);function Qs(t,e){for(const i in e)"Object"===$s(e[i])&&i in t?Qs(t[i],e[i]):t[i]=e[i];return t}function to(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function eo(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;i<t.length;i++)e[i]=eo(t[i])}else{e={};for(let i in t)t.hasOwnProperty(i)&&(e[i]=eo(t[i]))}return e}function io(t){if(!t)return!1;const e=t.name.toLowerCase();if(![".jpg",".jpeg",".ico",".gif",".svg",".webp",".png",".bmp"].some(t=>e.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const no="undefined"==typeof self,ro="function"==typeof importScripts,so=(()=>{if(!ro){if(!no&&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"./"}})(),oo=t=>{if(null==t&&(t="./"),no||ro);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Bt.engineResourcePaths.utility={version:"2.0.30-dev-20250708175811",path:so,isInternal:!0},kt.utility={js:!0,wasm:!0};const ao="2.0.0";"string"!=typeof Bt.engineResourcePaths.std&&N(Bt.engineResourcePaths.std.version,ao)<0&&(Bt.engineResourcePaths.std={version:ao,path:oo(so+`../../dynamsoft-capture-vision-std@${ao}/dist/`),isInternal:!0});const ho="3.0.10";(!Bt.engineResourcePaths.dip||"string"!=typeof Bt.engineResourcePaths.dip&&N(Bt.engineResourcePaths.dip.version,ho)<0)&&(Bt.engineResourcePaths.dip={version:ho,path:oo(so+`../../dynamsoft-image-processing@${ho}/dist/`),isInternal:!0});function lo(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"==typeof SuppressedError&&SuppressedError;const co="undefined"==typeof self,uo="function"==typeof importScripts,fo=(()=>{if(!uo){if(!co&&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"./"}})(),go=t=>{if(null==t&&(t="./"),co||uo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Bt.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:fo,isInternal:!0},kt.dbr={js:!1,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},Pt.dbr={};const mo="2.0.0";"string"!=typeof Bt.engineResourcePaths.std&&N(Bt.engineResourcePaths.std.version,mo)<0&&(Bt.engineResourcePaths.std={version:mo,path:go(fo+`../../dynamsoft-capture-vision-std@${mo}/dist/`),isInternal:!0});const po="3.0.10";(!Bt.engineResourcePaths.dip||"string"!=typeof Bt.engineResourcePaths.dip&&N(Bt.engineResourcePaths.dip.version,po)<0)&&(Bt.engineResourcePaths.dip={version:po,path:go(fo+`../../dynamsoft-image-processing@${po}/dist/`),isInternal:!0});const _o={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),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_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var vo,yo,wo,Co,Eo,So,bo,To,Io,xo;function Oo(t,e){let i=!0;for(let o=0;o<t.length;o++){const a=(o+1)%t.length;if(n=t[o],s=e,((r=t[a]).x-n.x)*(s.y-n.y)-(r.y-n.y)*(s.x-n.x)<0){i=!1;break}}var n,r,s;return i}function Ro(t,e){return Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2)}function Ao(t,e){const[i,n]=t,r=i.x,s=i.y,o=n.x,a=n.y,h=e.x,l=e.y,c=(o-r)**2+(a-s)**2;if(0===c)return Math.sqrt((h-r)**2+(l-s)**2);const u=((h-r)*(o-r)+(l-s)*(a-s))/c;if(u<0)return Math.sqrt((h-r)**2+(l-s)**2);if(u>1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Do(t){const e=[];for(let i=0;i<t.length;i++){const n=t[i],r=t[(i+1)%t.length];e.push([n,r])}return e}function Lo(t){const[e,i]=t;return{x:(e.x+i.x)/2,y:(e.y+i.y)/2}}function Mo(t,e,i,n){const r=e.x-t.x,s=e.y-t.y,o=n.x-i.x,a=n.y-i.y,h=(-s*(t.x-i.x)+r*(t.y-i.y))/(-o*s+r*a),l=(o*(t.y-i.y)-a*(t.x-i.x))/(-o*s+r*a);return h>=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Fo(t){let e=0;for(let i=0;i<t.length;i++){const n=(i+1)%t.length;e+=t[i].x*t[n].y,e-=t[n].x*t[i].y}return Math.abs(e/2)}function Po(t,e,i){let n=e.x-t.x,r=e.y-t.y,s=i.x-t.x;return n*(i.y-t.y)-r*s>0}function ko(t,e){for(let i=0;i<4;i++)if(!Po(t.points[i],t.points[(i+1)%4],e))return!1;return!0}(Eo=vo||(vo={}))[Eo.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",Eo[Eo.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",Eo[Eo.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(yo||(yo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(wo||(wo={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(Co||(Co={}));function No(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Do(r)[3],h=Do(r)[1],l=Do(s)[3],c=Do(s)[1];let u,d=0;if(u=Math.max(Math.abs(Ao(a,e.points[0])),Math.abs(Ao(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Ao(h,e.points[1])),Math.abs(Ao(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Ao(l,t.points[0])),Math.abs(Ao(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Ao(c,t.points[1])),Math.abs(Ao(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Lo(Do(r)[0]),g=Lo(Do(r)[2]),m=Lo(Do(s)[0]),p=Lo(Do(s)[2]),_=Ro(f,p),v=Ro(m,g),y=_>v,w=Math.min(_,v),C=Ro(f,g),E=Ro(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w<S||Oo(r,y?m:p)||Oo(s,y?g:f))&&(y?(n.points[0]=t.points[0],n.points[1]=t.points[1],n.points[2]=e.points[2],n.points[3]=e.points[3]):(n.points[0]=e.points[0],n.points[1]=e.points[1],n.points[2]=t.points[2],n.points[3]=t.points[3]),n.area=Fo(n.points),!0)}class Bo{constructor(t,e,i,n){this.overlapCount=t,this.verificationCount=e,this.crossVerificationFrame=5,this.location=n.location,this.locationArea=n.location.area,this.locationAngle=n.angle,this.format=n.format,this.text=n.text,this.isOneD=i,this.item=n,this.locationThreshold=5*n.moduleSize,this.strictLimit=Math.max(this.locationThreshold,1),this.strictLimit=Math.min(this.strictLimit,15)}getCenterPoint(t){const e={x:0,y:0};return t.forEach(({x:t,y:i})=>{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),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(ko(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(ko(this.location,e))return!0}else{for(let e=0;e<4;e++)if(ko(t,this.location.points[e]))return!0;if(ko(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(Ao(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;if(Math.abs(r.y+e.y-n.y)>=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=Mo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{Oo(e,t)&&i.push(t)}),e.forEach(e=>{Oo(t,e)&&i.push(e)}),Fo(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 jo={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Uo=t=>Object.values(jo).includes(t)||jo.hasOwnProperty(t),Vo=(t,e)=>"string"==typeof t?e[jo[t]]:e[t],Go=(t,e,i)=>{"string"==typeof t?e[jo[t]]=i:e[t]=i},Wo=(t,e,i)=>{const n=[{type:at.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:at.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class Yo{constructor(){this.verificationEnabled={[at.CRIT_BARCODE]:!1,[at.CRIT_TEXT_LINE]:!0,[at.CRIT_DETECTED_QUAD]:!0,[at.CRIT_DESKEWED_IMAGE]:!1},this.duplicateFilterEnabled={[at.CRIT_BARCODE]:!1,[at.CRIT_TEXT_LINE]:!1,[at.CRIT_DETECTED_QUAD]:!1,[at.CRIT_DESKEWED_IMAGE]:!1},this.duplicateForgetTime={[at.CRIT_BARCODE]:3e3,[at.CRIT_TEXT_LINE]:3e3,[at.CRIT_DETECTED_QUAD]:3e3,[at.CRIT_DESKEWED_IMAGE]:3e3},this.latestOverlappingEnabled={[at.CRIT_BARCODE]:!1,[at.CRIT_TEXT_LINE]:!1,[at.CRIT_DETECTED_QUAD]:!1,[at.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[at.CRIT_BARCODE]:5,[at.CRIT_TEXT_LINE]:5,[at.CRIT_DETECTED_QUAD]:5,[at.CRIT_DESKEWED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,So.set(this,new Map),bo.set(this,new Map),To.set(this,new Map),Io.set(this,new Map),xo.set(this,new Map),Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),Wo(this,t,at.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{Wo(this,t,at.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){lo(this,So,"f").forEach((t,e)=>{Go(e,this.verificationEnabled,t)}),lo(this,bo,"f").forEach((t,e)=>{Go(e,this.duplicateFilterEnabled,t)}),lo(this,To,"f").forEach((t,e)=>{Go(e,this.duplicateForgetTime,t)}),lo(this,Io,"f").forEach((t,e)=>{Go(e,this.latestOverlappingEnabled,t)}),lo(this,xo,"f").forEach((t,e)=>{Go(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){Uo(t)&&lo(this,So,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Uo(t)&&Vo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Uo(t)&&(e&&this.enableLatestOverlapping(t,!1),lo(this,bo,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Uo(t)&&Vo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Uo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),lo(this,To,"f").set(t,e))}getDuplicateForgetTime(t){return Uo(t)?Vo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Uo(t)&&lo(this,xo,"f").set(t,e)}getMaxOverlappingFrames(t){return Uo(t)?Vo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Uo(t)&&(e&&this.enableResultDeduplication(t,!1),lo(this,Io,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Uo(t)&&Vo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[at.CRIT_BARCODE,at.CRIT_TEXT_LINE,at.CRIT_DETECTED_QUAD,at.CRIT_DESKEWED_IMAGE];for(let i=0;i<e.length;i++)(this.verificationEnabled[e[i]]||this.duplicateFilterEnabled[e[i]])&&(t|=e[i]);return t}latestOverlappingFilter(t){var e,i,n;const r=this.isResultCrossVerificationEnabled(at.CRIT_BARCODE),s=this.isLatestOverlappingEnabled(at.CRIT_BARCODE);if(s){const o=5,a=60,h=s?this.getMaxOverlappingFrames(at.CRIT_BARCODE):5,l=t.items.length,c=null===(n=null===(i=null===(e=null==t?void 0:t.intermediateResult)||void 0===e?void 0:e[0])||void 0===i?void 0:i.intermediateResultUnits)||void 0===n?void 0:n[1].localizedBarcodes,u=c?c.length:0;let d=[];const f=[],g={x:0,y:0};let m=new Array(l).fill(-1),p=0;const _=t.items.map(t=>{if(1!==t.type){const e=(BigInt(t.format)&BigInt(_o.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(_o.BF_GS1_DATABAR))!=BigInt(0);return new Bo(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e<l;){const i={x:0,y:0},n=new Array(l).fill(-1);let r=!1;for(;e<l;e++){if(!_[e])continue;const s=_[e].item;for(let o=0;o<this.overlapSet.length;o++){if(t[e][o]<1)continue;const a=this.overlapSet[o],h=a.item;if(s.format===h.format&&s.text===h.text){if(r=a.isProbablySameLocationWithOffset(_[e],i),r){n[e]=o,t[e][o]=0;break}}else t[e][o]=0}if(r)break}if(r){for(let r=0;r<l;r++){if(r===e||!_[r])continue;const s=_[r].item;for(let e=0;e<this.overlapSet.length;e++){if(t[r][e]<1)continue;if(n.includes(e))continue;const o=this.overlapSet[e],a=o.item;if(s.format===a.format&&s.text===a.text){if(o.isMatchedLocationWithOffset(_[r],i)){n[r]=e,t[r][e]=0;break}}else t[r][e]=0}}const r=n.filter(t=>-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<l;e++){const i=_[e].item;for(let n=0;n<this.overlapSet.length;n++){if(t[e][n]<1)continue;if(m.includes(n))continue;const r=this.overlapSet[n],s=r.item;if(i.format===s.format&&i.text===s.text){if(r.isMatchedLocationWithOffset(_[e])){m[e]=n,t[e][n]=0;break}}else t[e][n]=0}}p+=m.filter(t=>-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<this.overlapSet.length;e++){const i=this.overlapSet[e];for(let e=0;e<u;e++)if(i.isOverlappedLocationWithOffset(c[e],g)){t++;break}}i=this.overlapSet.length<=3?t>=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(_o.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(_o.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence<a,o=new Bo(h,n?1:2,n,i);r&&n&&s&&f.push(e),this.overlapSet.push(o)}});else{let e=!0;s?(Math.abs(g.x)>5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i<t.items.length;i++){const t=m[i];if(t<0&&_[i]){const t=_[i].item;let n={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};for(let i=0;i<4;i++)n.points[i].x=e?t.location.points[i].x-g.x:t.location.points[i].x,n.points[i].y=e?t.location.points[i].y-g.y:t.location.points[i].y;for(let r=0;r<this.overlapSet.length;r++){if(m.includes(r))continue;const s=this.overlapSet[r].item.text,o=this.overlapSet[r].item.format;if(t.format===o&&t.text===s){if(this.overlapSet[r].isOverlappedLocationWithOffset(t,g,!1)){const e=Object.assign({},t),n=(BigInt(e.format)&BigInt(_o.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(_o.BF_GS1_DATABAR))!=BigInt(0),s=n?1:2;this.overlapSet[r]=new Bo(h,s,n,e),m[i]=r;break}if(_[i].isOneD){let s={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};for(let t=0;t<4;t++)s.points[t].x=e?this.overlapSet[r].location.points[t].x:this.overlapSet[r].location.points[t].x+g.x,s.points[t].y=e?this.overlapSet[r].location.points[t].y:this.overlapSet[r].location.points[t].y+g.y;let o={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};if(No(n,s,t.moduleSize,o)){t.location=o;const e=Object.assign({},t),n=(BigInt(e.format)&BigInt(_o.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(_o.BF_GS1_DATABAR))!=BigInt(0),s=n?1:2;this.overlapSet[r]=new Bo(h,s,n,e),m[i]=r;break}}}}}else{if(e)_[i]&&(_[i].item.location=this.overlapSet[t].location);else{const e=Object.assign({},_[i].item),n=(BigInt(e.format)&BigInt(_o.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(_o.BF_GS1_DATABAR))!=BigInt(0),r=n?1:2;this.overlapSet[t]=new Bo(h,r,n,e)}this.overlapSet[t]&&(this.overlapSet[t].overlapCount=h,this.overlapSet[t].verificationCount=2,this.overlapSet[t].crossVerificationFrame=o)}}e?this.stabilityCount<15&&this.stabilityCount++:this.stabilityCount=0;let i=!0;for(let t=0;t<this.overlapSet.length;t++){if(m.includes(t))continue;const n=this.overlapSet[t];n.overlapCount--,n.crossVerificationFrame--;const r=n.overlapCount+this.stabilityCount;if(s&&r>0){for(let t=0;t<l;t++)if(n.isOverlappedLocationWithOffset(_[t],g,!1)){i=!1;break}if(!i)break;const t=n.item;if(!e){for(let t=0;t<4;t++)n.location.points[t].x+=g.x,n.location.points[t].y+=g.y;t.location=n.location}2===n.verificationCount&&d.push(t)}}if(s&&!i){d=[];for(let t=0;t<this.overlapSet.length;t++){if(m.includes(t))continue;const e=this.overlapSet[t];e.overlapCount=0-this.stabilityCount,e.crossVerificationFrame=0,e.verificationCount=0}}for(let t=0;t<l;t++){if(-1!==m[t]||!_[t])continue;const i=_[t].item;if(e){for(let e=0;e<4;e++)_[t].location.points[e].x-=g.x,_[t].location.points[e].y-=g.y;i.location=_[t].location}let n=!1;for(let e of this.overlapSet)if(!(e.crossVerificationFrame<=0&&e.verificationCount<=0)&&(n=e.isLocationOverlap(_[t].location,_[t].locationArea),n))break;if(n){f.push(t);continue}const s=Object.assign({},i),o=(BigInt(i.format)&BigInt(_o.BF_ONED))!=BigInt(0)||(BigInt(i.format)&BigInt(_o.BF_GS1_DATABAR))!=BigInt(0),l=i.confidence<a,c=new Bo(h,o?1:2,o,s);r&&o&&l?f.push(t):c.verificationCount=2,this.overlapSet.push(c)}this.overlapSet=this.overlapSet.filter(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}))})}}}So=new WeakMap,bo=new WeakMap,To=new WeakMap,Io=new WeakMap,xo=new WeakMap;var Ho,Xo,zo,qo,Ko,Zo,Jo,$o,Qo,ta,ea,ia,na,ra,sa,oa,aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a=Object.freeze({__proto__:null,MultiFrameResultCrossFilter:Yo,UtilityModule:class{static getVersion(){return`2.0.30-dev-20250708175811(Worker: ${Ft.utility&&Ft.utility.worker||"Not Loaded"}, Wasm: ${Ft.utility&&Ft.utility.wasm||"Not Loaded"})`}}});class va{constructor(e){if(Ho.add(this),qo.set(this,void 0),Ko.set(this,{status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]}),Zo.set(this,!1),Jo.set(this,void 0),$o.set(this,void 0),Qo.set(this,void 0),ta.set(this,void 0),this.config=eo(Ut),e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";Qs(this.config,e),ps._isRTU=!0}launch(){return e(this,void 0,void 0,function*(){if(i(this,Zo,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(i(va,Xo,"f",zo)&&!i(va,Xo,"f",zo).isFulfilled&&!i(va,Xo,"f",zo).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return n(va,Xo,new Wt,"f",zo),yield i(this,Ho,"m",ea).call(this),i(va,Xo,"f",zo)})}decode(t,r="ReadBarcodes_Default"){return e(this,void 0,void 0,function*(){n(this,$o,r,"f"),yield i(this,Ho,"m",ia).call(this,!0),i(this,ta,"f")||n(this,ta,new Yo,"f"),i(this,ta,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(i(this,ta,"f"));const e=new Me;e.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(e);const s=yield this._cvRouter.capture(t,r);return i(this,ta,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(i(this,ta,"f")),this._cvRouter.removeResultReceiver(e),s})}dispose(){var t,e,r,s,o,a,h;n(this,Zo,!0,"f"),i(va,Xo,"f",zo)&&i(va,Xo,"f",zo).isPending&&i(va,Xo,"f",zo).resolve(i(this,Ko,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(e=this._cameraView)||void 0===e||e.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",i(this,qo,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}Xo=va,qo=new WeakMap,Ko=new WeakMap,Zo=new WeakMap,Jo=new WeakMap,$o=new WeakMap,Qo=new WeakMap,ta=new WeakMap,Ho=new WeakSet,ea=function(){return e(this,void 0,void 0,function*(){try{this.config.onInitPrepare&&this.config.onInitPrepare(),yield i(this,Ho,"m",ia).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter});try{document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),to(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})}catch(t){i(this,Ho,"m",fa).call(this),i(this,Ho,"m",ga).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";document.querySelector(".no-camera-view").style.display="flex"}yield this._cvRouter.startCapturing(i(this,$o,"f"))}catch(e){i(this,Ko,"f").status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(va,Xo,"f",zo).reject(new Error(i(this,Ko,"f").status.message)),this.dispose()}finally{i(this,Ho,"m",ma).call(this,"Loading...",!1)}})},ia=function(r=!1){return e(this,void 0,void 0,function*(){if(Bt.engineResourcePaths=this.config.engineResourcePaths,!r){const e=B(Bt.engineResourcePaths);if(this._cameraView=yield Sr.createInstance(e.dbrBundle+"ui/dce.ui.xml"),this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),this._cameraEnhancer=yield ps.createInstance(this._cameraView),yield i(this,Ho,"m",ra).call(this),this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1),n(this,Qo,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}}yield qs.initLicense(this.config.license||"",{executeNow:!0}),this._cvRouter=this._cvRouter||(yield Le.createInstance()),this.config.scanMode!==t.EnumScanMode.SM_SINGLE||r?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{i(va,Xo,"f",zo).reject(new Error(t.message)),this.dispose()},yield i(this,Ho,"m",na).call(this,r),r||(this._cvRouter.setInput(this._cameraEnhancer),i(this,Ho,"m",sa).call(this),yield i(this,Ho,"m",oa).call(this))})},na=function(r=!1){return e(this,void 0,void 0,function*(){r||(this.config.scanMode===t.EnumScanMode.SM_SINGLE?n(this,$o,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&n(this,$o,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath));const e=yield this._cvRouter.getSimplifiedSettings(i(this,$o,"f"));r||this.config.scanMode!==t.EnumScanMode.SM_SINGLE||(e.outputOriginalImage=!0);let s=this.config.barcodeFormats;if(s){Array.isArray(s)||(s=[s]),e.barcodeSettings.barcodeFormatIds=BigInt(0);for(let t=0;t<s.length;t++){if("bigint"!=typeof s[t])throw new Error(`Invalid barcodeFormats [${s[t]}] Index ${t}.`);e.barcodeSettings.barcodeFormatIds|=s[t]}}yield this._cvRouter.updateSettings(i(this,$o,"f"),e)})},ra=function(){var r,s,o,h,l,c,u,d,f;return e(this,void 0,void 0,function*(){const g=this.config.uiPath,m=g.endsWith("/")?a(g)+"ui/barcode-scanner.ui.xml":a(g).slice(0,-1),p=yield(_=m,e(void 0,void 0,void 0,function*(){if("string"!=typeof _)throw new TypeError("Invalid url.");const t=yield fetch(_);if(!t.ok)throw Error("Network Error: "+t.statusText);const e=yield t.text();if(!e.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const i=document.createElement("div");if(i.insertAdjacentHTML("beforeend",e),1===i.childElementCount&&i.firstChild instanceof HTMLTemplateElement)return i.firstChild.content;const n=new DocumentFragment;for(let t of i.children)n.append(t);return n}));var _;p.querySelectorAll("style").forEach(t=>{document.head.appendChild(t.cloneNode(!0))}),n(this,Jo,p.querySelector(".result-item"),"f");const y=p.querySelector(".btn-clear");if(y&&(y.addEventListener("click",()=>{i(this,Ko,"f").barcodeResults=[],i(this,Ho,"m",ua).call(this)}),null===(o=null===(s=null===(r=this.config)||void 0===r?void 0:r.resultViewConfig)||void 0===s?void 0:s.toolbarButtonsConfig)||void 0===o?void 0:o.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;y.style.display=t.isHidden?"none":"flex",y.className=t.className?t.className:"btn-clear",y.innerText=t.label?t.label:"Clear",t.isHidden&&(p.querySelector(".toolbar-btns").style.justifyContent="center")}const w=p.querySelector(".btn-done");if(w&&(w.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(c=null===(l=null===(h=this.config)||void 0===h?void 0:h.resultViewConfig)||void 0===l?void 0:l.toolbarButtonsConfig)||void 0===c?void 0:c.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;w.style.display=t.isHidden?"none":"flex",w.className=t.className?t.className:"btn-done",w.innerText=t.label?t.label:"Done",t.isHidden&&(p.querySelector(".toolbar-btns").style.justifyContent="center")}if(null===(d=null===(u=this.config)||void 0===u?void 0:u.scannerViewConfig)||void 0===d?void 0:d.showCloseButton){const e=p.querySelector(".btn-close");e&&(e.style.display="",e.addEventListener("click",()=>{i(this,Ko,"f").barcodeResults=[],i(this,Ko,"f").status={code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}if(null===(f=this.config)||void 0===f?void 0:f.scannerViewConfig.showFlashButton){const t=p.querySelector(".btn-flash-auto"),n=p.querySelector(".btn-flash-open"),r=p.querySelector(".btn-flash-close");if(t){t.style.display="";let s=null,o=250,a=20,h=3;const l=(l=250)=>e(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==s){if(!(l<o))return;clearInterval(s),s=null}o=l;let u=!1,d=0,f=0;const g=()=>e(this,void 0,void 0,function*(){var e;if(i(this,Zo,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(s),void(s=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(s),s=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(v.IPF_GRAYSCALED===l.format){for(let t=0;t<l.bytes.length;++t)c+=l.bytes[t];c/=l.bytes.length}else{if(v.IPF_ABGR_8888!==l.format)return;for(let t=0;t<l.bytes.length;t+=4)c+=l.bytes[t],c+=l.bytes[t+1],c+=l.bytes[t+2];c/=l.bytes.length/4*3}if(c<a){if(++d>=h){null===(e=ps._onLog)||void 0===e||e.call(ps,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,t.style.display="none",n.style.display="",r.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});s=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&i(this,Ho,"m",ga).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),t.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),t.style.display="none",n.style.display="",r.style.display="none"})),n.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),t.style.display="none",n.style.display="none",r.style.display=""})),r.addEventListener("click",()=>e(this,void 0,void 0,function*(){l(1e3),t.style.display="",n.style.display="none",r.style.display="none"}))}}let C=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(C)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const t=p.querySelector(".camera-control");if(t){t.style.display="";const n=yield this._cameraEnhancer.getAllCameras(),r=this.config.scannerViewConfig.cameraSwitchControl,s=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px"}),e},o=()=>{if(0===n.length)return null;if("listAll"===r){const t=p.querySelector(".camera-list");for(let e of n){const i=s(e);t.append(i)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const r=t=>{for(let e of o)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};t.addEventListener("click",t=>e(this,void 0,void 0,function*(){const e=t.target;i(this,Ho,"m",ma).call(this,"Accessing Camera...",!0),yield this._cameraEnhancer.selectCamera({deviceId:e.deviceId,label:e.label,_checked:e._checked});const n=this._cameraEnhancer.getSelectedCamera(),s=this._cameraEnhancer.getCapabilities();to(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(s.torch?i(this,Ho,"m",ga).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):i(this,Ho,"m",ga).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),r(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),i(this,Ho,"m",ma).call(this,"Loading...",!1)}));const o=p.querySelectorAll(".camera-list div");return()=>e(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();r(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===r?()=>e(this,void 0,void 0,function*(){i(this,Ho,"m",ma).call(this,"Accessing Camera...",!0);const t=to(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&i(this,Ho,"m",ga).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&i(this,Ho,"m",ga).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),i(this,Ho,"m",ma).call(this,"Loading...",!1)}):void 0},a=o();t.addEventListener("click",t=>e(this,void 0,void 0,function*(){t.stopPropagation(),a&&(yield a())}))}}this.config.showUploadImageButton&&i(this,Ho,"m",fa).call(this,p.querySelector(".btn-upload-image"));const E=this._cameraView.getUIElement();E.shadowRoot.querySelector(".dce-sel-camera").remove(),E.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const S=p.querySelector(".barcode-scanner-container");S.style.display=Js()?"flex":"",this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this.config.showResultView=!1);const b=this.config.showResultView;let T;if(this.config.container?(S.style.position="relative",T=this.config.container):T=document.body,"string"==typeof T&&(T=document.querySelector(T),null===T))throw new Error("Failed to get the container");let I=this.config.scannerViewConfig.container;if("string"==typeof I&&(I=document.querySelector(I),null===I))throw new Error("Failed to get the container of the scanner view.");let x=this.config.resultViewConfig.container;if("string"==typeof x&&(x=document.querySelector(x),null===x))throw new Error("Failed to get the container of the result view.");const O=p.querySelector(".scanner-view-container"),R=p.querySelector(".result-view-container"),A=p.querySelector(".loading-page");O.append(A),I&&(O.append(E),I.append(O)),x&&x.append(R),I||x?I&&!x?(this.config.container||(R.style.position="absolute"),x=R,T.append(R)):!I&&x&&(this.config.container||(O.style.position="absolute"),I=O,O.append(E),T.append(O)):(I=O,x=R,b&&(Object.assign(O.style,{width:Js()?"50%":"100%",height:Js()?"100%":"50%"}),Object.assign(R.style,{width:Js()?"50%":"100%",height:Js()?"100%":"50%"})),O.append(E),T.append(S)),document.querySelector(".result-view-container").style.display=b?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),n(this,qo,()=>{Object.assign(S.style,{display:Js()?"flex":""}),!b||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(I.style,{width:Js()?"50%":"100%",height:Js()?"100%":"50%"}),Object.assign(x.style,{width:Js()?"50%":"100%",height:Js()?"100%":"50%"}))},"f"),window.addEventListener("resize",i(this,qo,"f")),this._cameraView._createDrawingLayer(2)})},sa=function(){const n=new Me;n.onCapturedResultReceived=n=>e(this,void 0,void 0,function*(){if(i(this,Qo,"f")&&i(this,Qo,"f").clearDrawingItems(),n.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of n.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));i(this,Qo,"f").addDrawingItems(t)}this.config.scanMode===t.EnumScanMode.SM_SINGLE?i(this,Ho,"m",aa).call(this,n):i(this,Ho,"m",ha).call(this,n)}}),this._cvRouter.addResultReceiver(n)},oa=function(){return e(this,void 0,void 0,function*(){i(this,ta,"f")||n(this,ta,new Yo,"f"),i(this,ta,"f").enableResultCrossVerification(2,!0),i(this,ta,"f").enableResultDeduplication(2,!0),i(this,ta,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(i(this,ta,"f")),i(this,ta,"f").isResultCrossVerificationEnabled=()=>!1,i(this,ta,"f").isResultDeduplicationEnabled=()=>!1})},aa=function(e){const n=this._cameraView.getUIElement().shadowRoot;let r=new Promise(t=>{if(e.decodedBarcodesResult.barcodeResultItems.length>1){i(this,Ho,"m",ca).call(this);for(let i of e.decodedBarcodesResult.barcodeResultItems){let e=0,r=0;for(let t=0;t<4;++t){let n=i.location.points[t];e+=n.x,r+=n.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"32px",height:"32px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{t(i)}),n.append(o)}}else t(e.decodedBarcodesResult.barcodeResultItems[0])});r.then(n=>{const r=e.items.filter(t=>t.type===at.CRIT_ORIGINAL_IMAGE)[0].imageData,s={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},originalImageResult:r,barcodeImage:(()=>{const t=j(r),e=n.location.points,i=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-i,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-i,e[0].y-s);for(let t=1;t<e.length;t++)u.lineTo(e[t].x-i,e[t].y-s);u.closePath(),u.clip(),u.drawImage(t,-i,-s);const d=u.getImageData(0,0,c.width,c.height);return{bytes:new Uint8Array(d.data),width:d.width,height:d.height,stride:4*d.width,format:v.IPF_ARGB_8888}})(),barcodeResults:[n]};i(this,Ho,"m",pa).call(this,n),i(va,Xo,"f",zo).resolve(s),this.dispose()})},ha=function(t){for(let e of t.decodedBarcodesResult.barcodeResultItems){if(!1!==e.duplicate)continue;const t=i(this,Ko,"f").barcodeResults.findIndex(t=>`${t.formatString}_${t.text}`==`${e.formatString}_${e.text}`);-1===t?(e.count=1,i(this,Ko,"f").barcodeResults.unshift(e),i(this,Ho,"m",ua).call(this,e)):(i(this,Ko,"f").barcodeResults[t].count++,i(this,Ho,"m",da).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(e)}},la=function(t){const e=i(this,Jo,"f").cloneNode(!0);e.querySelector(".format-string").innerText=t.formatString;e.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),e.id=`${t.formatString}_${t.text}`;return e.querySelector(".delete-icon").addEventListener("click",()=>{const e=[...document.querySelectorAll(".main-list .result-item")],n=e.findIndex(e=>e.id===`${t.formatString}_${t.text}`);i(this,Ko,"f").barcodeResults.splice(n,1),e[n].remove(),0===i(this,Ko,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),e},ca=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},ua=function(e){if(!this.config.showResultView)return;const n=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==t.EnumScanMode.SM_SINGLE))return;const r=document.querySelector(".main-list");if(!e)return r.textContent="",void(this.config.showPoweredByDynamsoft&&(n.style.display=""));n.style.display="none";const s=i(this,Ho,"m",la).call(this,e);r.insertBefore(s,document.querySelector(".result-item"))},da=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},fa=function(n){n||(n=document.querySelector(".btn-upload-image")),n&&(n.style.display="",n.onchange=n=>e(this,void 0,void 0,function*(){const e=n.target.files,r={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]};let s=0;i(this,Ho,"m",ma).call(this,`Capturing... [${s}/${e.length}]`,!0);let o=!1;for(let t=0;t<e.length;t++)if(!io(e[t])){o=!0;break}if(o)return i(va,Xo,"f",zo).reject(new Error("Upload failed: one or more files are in unsupported formats. Please make sure all files are .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp.")),void this.dispose();for(let n of e)try{const o=yield this.decode(n,this.config.utilizedTemplateNames.image);if(o.decodedBarcodesResult)if(this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE)for(let t of o.decodedBarcodesResult.barcodeResultItems){const e=i(this,Ko,"f").barcodeResults.findIndex(e=>`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===e?(t.count=1,i(this,Ko,"f").barcodeResults.unshift(t),i(this,Ho,"m",ua).call(this,t)):(i(this,Ko,"f").barcodeResults[e].count++,i(this,Ho,"m",da).call(this,e))}else if(o.decodedBarcodesResult.barcodeResultItems)for(let t of o.decodedBarcodesResult.barcodeResultItems){const e=r.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,r.barcodeResults.push(t))}i(this,Ho,"m",ma).call(this,`Capturing... [${++s}/${e.length}]`,!0)}catch(e){r.status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(va,Xo,"f",zo).reject(new Error(r.status.message)),this.dispose()}i(this,Ho,"m",ma).call(this,"Loading...",!1),this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(i(va,Xo,"f",zo).resolve(r),this.dispose()),n.target.value=""}))},ga=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},ma=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},pa=function(t){let e=Ot();Rt[e]=()=>{},It.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},zo={value:null};const ya="undefined"==typeof self,wa="function"==typeof importScripts,Ca=(()=>{if(!wa){if(!ya&&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"./"}})(),Ea=t=>{if(null==t&&(t="./"),ya||wa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Bt.engineResourcePaths.dbr={version:"11.0.30-dev-20250708180832",path:Ca,isInternal:!0},kt.dbr={js:!1,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},Pt.dbr={};const Sa="2.0.0";"string"!=typeof Bt.engineResourcePaths.std&&N(Bt.engineResourcePaths.std.version,Sa)<0&&(Bt.engineResourcePaths.std={version:Sa,path:Ea(Ca+`../../dynamsoft-capture-vision-std@${Sa}/dist/`),isInternal:!0});const ba="3.0.10";(!Bt.engineResourcePaths.dip||"string"!=typeof Bt.engineResourcePaths.dip&&N(Bt.engineResourcePaths.dip.version,ba)<0)&&(Bt.engineResourcePaths.dip={version:ba,path:Ea(Ca+`../../dynamsoft-image-processing@${ba}/dist/`),isInternal:!0});const Ta={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),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_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Ia,xa,Oa,Ra;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(Ia||(Ia={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(xa||(xa={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(Oa||(Oa={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(Ra||(Ra={}));var Aa,Da,La=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=Ft.dbr&&Ft.dbr.wasm;return`11.0.30-dev-20250708180832(Worker: ${Ft.dbr&&Ft.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:Ta,get EnumDeblurMode(){return Ra},get EnumExtendedBarcodeResultType(){return Ia},get EnumLocalizationMode(){return Oa},get EnumQRCodeErrorCorrectionLevel(){return xa}});function Ma(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Fa(e,t,"map"),t.getFieldRawValue=t=>Fa(e,t,"raw"),t.getFieldMappingStatus=t=>Pa(e,t),t.getFieldValidationStatus=t=>ka(e,t),delete t.fullCodeString}function Fa(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=Fa(r,e,i);if(void 0!==t)return t}}}function Pa(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Aa[i.MappingStatus]):Aa.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=Pa(n,e);if(void 0!==t)return t}}}function ka(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(Da[i.ValidationStatus]):Da.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=ka(n,e);if(void 0!==t)return t}}}function Na(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"}(Aa||(Aa={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(Da||(Da={}));const Ba=t=>t&&"object"==typeof t&&"function"==typeof t.then,ja=(async()=>{})().constructor;class Ua extends ja{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,Ba(t)?e=t:"function"==typeof t&&(e=new ja(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&&(Ba(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class Va{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!Pt.license)throw Error("Module `license` is not existed.");await Pt.license.dynamsoft(),await Bt.loadWasm();const t=new Va,e=new Ua;let i=Ot();return Rt[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},It.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){Na(this);let t=Ot();this.bDestroyed=!0,Rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},It.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){return Na(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await k(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Ot();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)}},It.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})})):console.error("Invalid settings.")}async resetSettings(){return Na(this),await new Promise((t,e)=>{let i=Ot();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)}},It.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(Na(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<t.length;++i)e.push(t.charCodeAt(i));return e}(t))),Rt[r]=async t=>{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(Ma(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},It.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const Ga="undefined"==typeof self,Wa="function"==typeof importScripts,Ya=(()=>{if(!Wa){if(!Ga&&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"./"}})();Bt.engineResourcePaths.dcp={version:"3.0.30-dev-20250708175715",path:Ya,isInternal:!0},kt.dcp={js:!0,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE]},Pt.dcp={handleParsedResultItem:Ma};const Ha="2.0.0";"string"!=typeof Bt.engineResourcePaths.std&&N(Bt.engineResourcePaths.std.version,Ha)<0&&(Bt.engineResourcePaths.std={version:Ha,path:(t=>{if(null==t&&(t="./"),Ga||Wa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Ya+`../../dynamsoft-capture-vision-std@${Ha}/dist/`),isInternal:!0});var Xa=Object.freeze({__proto__:null,CodeParser:Va,CodeParserModule:class{static getVersion(){const t=Ft.dcp&&Ft.dcp.wasm;return`3.0.30-dev-20250708175715(Worker: ${Ft.dcp&&Ft.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await Bt.loadWasm(),await new Promise((i,n)=>{let r=Ot();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],o=B(Bt.engineResourcePaths);It.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===Bt._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}},get EnumMappingStatus(){return Aa},get EnumValidationStatus(){return Da}});Bt._bundleEnv="DBR",Le._defaultTemplate="ReadSingleBarcode",Bt.engineResourcePaths.dbrBundle={version:"11.0.3000",path:o,isInternal:!0},t.BarcodeScanner=va,t.CVR=Pe,t.Core=jt,t.DBR=La,t.DCE=xs,t.DCP=Xa,t.License=Zs,t.Utility=_a});
11
+ !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";function e(t,e,i,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function i(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 n(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const r="undefined"==typeof self,s="function"==typeof importScripts,o=(()=>{if(!s){if(!r&&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"./"}})(),a=t=>{if(null==t&&(t="./"),r||s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var h,l,c;t.EnumScanMode=void 0,(h=t.EnumScanMode||(t.EnumScanMode={}))[h.SM_SINGLE=0]="SM_SINGLE",h[h.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE",t.EnumOptimizationMode=void 0,(l=t.EnumOptimizationMode||(t.EnumOptimizationMode={}))[l.OM_NONE=0]="OM_NONE",l[l.OM_SPEED=1]="OM_SPEED",l[l.OM_COVERAGE=2]="OM_COVERAGE",l[l.OM_BALANCE=3]="OM_BALANCE",l[l.OM_DPM=4]="OM_DPM",l[l.OM_DENSE=5]="OM_DENSE",t.EnumResultStatus=void 0,(c=t.EnumResultStatus||(t.EnumResultStatus={}))[c.RS_SUCCESS=0]="RS_SUCCESS",c[c.RS_CANCELLED=1]="RS_CANCELLED",c[c.RS_FAILED=2]="RS_FAILED";const u=t=>t&&"object"==typeof t&&"function"==typeof t.then,d=(async()=>{})().constructor;let f=class extends d{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,u(t)?e=t:"function"==typeof t&&(e=new d(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&&(u(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function g(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 m(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var p,_,v;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(p||(p={})),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"}(_||(_={})),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"}(v||(v={}));const y="undefined"==typeof self,w="function"==typeof importScripts,E=(()=>{if(!w){if(!y&&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"./"}})(),C=t=>{if(null==t&&(t="./"),y||w);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},S=t=>Object.prototype.toString.call(t),b=t=>Array.isArray?Array.isArray(t):"[object Array]"===S(t),T=t=>"number"==typeof t&&!Number.isNaN(t),I=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),x=t=>!(!I(t)||!T(t.width)||t.width<=0||!T(t.height)||t.height<=0||!T(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!A(t.tag)),O=t=>!!x(t)&&t.bytes instanceof Uint8Array,R=t=>!(!I(t)||!T(t.left)||t.left<0||!T(t.top)||t.top<0||!T(t.right)||t.right<0||!T(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),A=t=>null===t||!!I(t)&&!!T(t.imageId)&&"type"in t,D=t=>!(!I(t)||!L(t.startPoint)||!L(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),L=t=>!!I(t)&&!!T(t.x)&&!!T(t.y),M=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),F=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!L(t)),P=t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.width)||t.width<0||!T(t.height)||t.height<0),k=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))}}),N=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t<i.length&&t<n.length;++t){let e=i[t],r=n[t];if(e===r)continue;let s=parseInt(i[t]),o=parseInt(n[t]);return s===o||Number.isNaN(s)&&Number.isNaN(o)?e<r?-1:1:s<o||Number.isNaN(s)&&Number.isInteger(o)?-1:1}return i.length===n.length?0:i.length<n.length?-1:1},B=t=>{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${W[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${W[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},j=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await V(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),U=t=>{O(t)&&(t=G(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},V=async(t,e)=>{O(e)&&(e=G(e));const i=U(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},G=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===v.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;++n)e[4*n]=i[3*n],e[4*n+1]=i[3*n+1],e[4*n+2]=i[3*n+2],e[4*n+3]=255}else if(Number(t.format)===v.IPF_RGB_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;++n)e[4*n]=i[3*n+2],e[4*n+1]=i[3*n+1],e[4*n+2]=i[3*n],e[4*n+3]=255}else if(Number(t.format)===v.IPF_GRAYSCALED){const t=i.length;e=new Uint8ClampedArray(4*t);for(let n=0;n<t;n++)e[4*n]=e[4*n+1]=e[4*n+2]=i[n],e[4*n+3]=255}else if(Number(t.format)===v.IPF_BINARY_8){const n=i.length,r=t.width,s=t.height,o=t.stride;e=new Uint8ClampedArray(r*s*4);for(let t=0;t<n;t++){let n=i[t],s=t%o,a=Math.floor(t/o);for(let t=0;t<8;t++){let i=s+t,o=4*(a*r+i);if(i>=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===v.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n<t;++n)e[4*n]=i[4*n],e[4*n+1]=i[4*n+1],e[4*n+2]=i[4*n+2],e[4*n+3]=i[4*n+3]}else if(Number(t.format)===v.IPF_ARGB_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n<t;++n)e[4*n]=i[4*n+2],e[4*n+1]=i[4*n+1],e[4*n+2]=i[4*n],e[4*n+3]=i[4*n+3]}else if(Number(t.format)===v.IPF_BINARY_8_INVERTED){const n=i.length,r=t.width,s=t.height,o=t.stride;e=new Uint8ClampedArray(r*s*4);for(let t=0;t<n;t++){let n=i[t],s=t%o,a=Math.floor(t/o);for(let t=0;t<8;t++){let i=s+t,o=4*(a*r+i);if(i>=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},W={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",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var Y,H,X,z,q,K,Z,J;let $,Q,tt,et,it,nt=class t{get _isFetchingStarted(){return g(this,q,"f")}constructor(){Y.add(this),H.set(this,[]),X.set(this,1),z.set(this,p.BOPM_BLOCK),q.set(this,!1),K.set(this,void 0),Z.set(this,_.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!O(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(g(this,H,"f").length>=g(this,X,"f"))switch(g(this,z,"f")){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:if(g(this,H,"f").push(t),I(g(this,K,"f"))&&T(g(this,K,"f").imageId)&&1==g(this,K,"f").keepInBuffer)for(;g(this,H,"f").length>g(this,X,"f");){const t=g(this,H,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==g(this,K,"f").imageId});g(this,H,"f").splice(t,1)}else g(this,H,"f").splice(0,g(this,H,"f").length-g(this,X,"f"))}else g(this,H,"f").push(t)}getImage(){if(0===g(this,H,"f").length)return null;let e;if(g(this,K,"f")&&T(g(this,K,"f").imageId)){const t=g(this,Y,"m",J).call(this,g(this,K,"f").imageId);if(t<0)throw new Error(`Image with id ${g(this,K,"f").imageId} doesn't exist.`);e=g(this,H,"f").slice(t,t+1)[0]}else e=g(this,H,"f").pop();if([v.IPF_RGB_565,v.IPF_RGB_555,v.IPF_RGB_888,v.IPF_ARGB_8888,v.IPF_RGB_161616,v.IPF_ARGB_16161616,v.IPF_ABGR_8888,v.IPF_ABGR_16161616,v.IPF_BGR_888].includes(e.format)){if(g(this,Z,"f")===_.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;t<i.length;t++)switch(e.format){case v.IPF_RGB_565:case v.IPF_RGB_555:case v.IPF_RGB_888:case v.IPF_RGB_161616:i[t]=e.bytes[3*t+2];break;case v.IPF_ARGB_8888:case v.IPF_ARGB_16161616:i[t]=e.bytes[4*t+2];break;case v.IPF_BGR_888:i[t]=e.bytes[3*t];break;case v.IPF_ABGR_8888:case v.IPF_ABGR_16161616:i[t]=e.bytes[4*t]}e.bytes=i,e.stride=e.width,e.format=v.IPF_GRAYSCALED}else if(g(this,Z,"f")===_.CCUT_RGB_G_CHANNEL_ONLY){t._onLog&&t._onLog("only get G channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case v.IPF_RGB_565:case v.IPF_RGB_555:case v.IPF_RGB_888:case v.IPF_RGB_161616:case v.IPF_BGR_888:i[t]=e.bytes[3*t+1];break;case v.IPF_ARGB_8888:case v.IPF_ARGB_16161616:case v.IPF_ABGR_8888:case v.IPF_ABGR_16161616:i[t]=e.bytes[4*t+1]}e.bytes=i,e.stride=e.width,e.format=v.IPF_GRAYSCALED}else if(g(this,Z,"f")===_.CCUT_RGB_B_CHANNEL_ONLY){t._onLog&&t._onLog("only get B channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t<i.length;t++)switch(e.format){case v.IPF_RGB_565:case v.IPF_RGB_555:case v.IPF_RGB_888:case v.IPF_RGB_161616:i[t]=e.bytes[3*t];break;case v.IPF_ARGB_8888:case v.IPF_ARGB_16161616:i[t]=e.bytes[4*t];break;case v.IPF_BGR_888:i[t]=e.bytes[3*t+2];break;case v.IPF_ABGR_8888:case v.IPF_ABGR_16161616:i[t]=e.bytes[4*t+2]}e.bytes=i,e.stride=e.width,e.format=v.IPF_GRAYSCALED}}else[v.IPF_NV21,v.IPF_NV12].includes(e.format)&&t._onLog&&t._onLog("NV21 or NV12 is not supported.");return e}setNextImageToReturn(t,e){if(!((...t)=>0!==t.length&&t.every(t=>T(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==S(e))throw new TypeError("Invalid 'keepInBuffer'.");m(this,K,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){m(this,K,null,"f")}hasImage(t){return g(this,Y,"m",J).call(this,t)>=0}startFetching(){m(this,q,!0,"f")}stopFetching(){m(this,q,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(m(this,X,t,"f");g(this,H,"f")&&g(this,H,"f").length>t;)g(this,H,"f").shift()}getMaxImageCount(){return g(this,X,"f")}getImageCount(){return g(this,H,"f").length}clearBuffer(){g(this,H,"f").length=0}isBufferEmpty(){return 0===g(this,H,"f").length}setBufferOverflowProtectionMode(t){m(this,z,t,"f")}getBufferOverflowProtectionMode(){return g(this,z,"f")}setColourChannelUsageType(t){m(this,Z,t,"f")}getColourChannelUsageType(){return g(this,Z,"f")}};H=new WeakMap,X=new WeakMap,z=new WeakMap,q=new WeakMap,K=new WeakMap,Z=new WeakMap,Y=new WeakSet,J=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return g(this,H,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&($=navigator,Q=$.userAgent,tt=$.platform,et=$.mediaDevices),function(){if(!y){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:$.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:tt,search:"Win"},Mac:{str:tt},Linux:{str:tt}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Q,o=r.search||e,a=r.verStr||Q,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Q,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Q.indexOf("Windows NT")&&(r="HarmonyOS"),it={browser:i,version:n,OS:r}}y&&(it={browser:"ssr",version:0,OS:"ssr"})}();const rt="undefined"!=typeof WebAssembly&&Q&&!(/Safari/.test(Q)&&!/Chrome/.test(Q)&&/\(.+\s11_2_([2-6]).*\)/.test(Q)),st=!("undefined"==typeof Worker),ot=!(!et||!et.getUserMedia),at=async()=>{let t=!1;if(ot)try{(await et.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var ht,lt,ct,ut,dt,ft,gt,mt,pt;"Chrome"===it.browser&&it.version>66||"Safari"===it.browser&&it.version>13||"OPR"===it.browser&&it.version>43||"Edge"===it.browser&&it.version,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_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(ht||(ht={})),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"}(lt||(lt={})),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_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",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_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",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_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",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_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",t[t.GEM_END=-1]="GEM_END"}(ut||(ut={})),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",t[t.GTM_END=-1]="GTM_END"}(dt||(dt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(ft||(ft={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(gt||(gt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(mt||(mt={})),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"}(pt||(pt={}));const _t={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_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_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_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var vt,yt,wt,Et,Ct,St;!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_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(vt||(vt={})),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_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(yt||(yt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(wt||(wt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(Et||(Et={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(Ct||(Ct={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(St||(St={}));const bt={},Tt=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(bt[t]=bt[t]||new f);await Promise.all(i)},It=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=bt[t]=bt[t]||new f(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let xt,Ot=0;const Rt=()=>Ot++,At={};let Dt;const Lt=t=>{Dt=t,xt&&xt.postMessage({type:"setBLog",body:{value:!!t}})};let Mt=!1;const Ft=t=>{Mt=t,xt&&xt.postMessage({type:"setBDebug",body:{value:!!t}})},Pt={},kt={},Nt={dip:{wasm:!0}},Bt={std:{version:"2.0.0",path:C(E+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.0.60-dev-20250812165815",path:E,isInternal:!0}};class jt{static get engineResourcePaths(){return Bt}static set engineResourcePaths(t){Object.assign(Bt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return Dt}static set _onLog(t){Lt(t)}static get _bDebug(){return Mt}static set _bDebug(t){Ft(t)}static get _workerName(){return`${jt._bundleEnv.toLowerCase()}.bundle.worker.js`}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!bt[t]&&bt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=bt.core;e=!i||i.isEmpty,e||await Tt("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),Ct.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||Ct.MN_DYNAMSOFT_CORE==t)return;let e=Nt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=bt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await It(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await Tt(o);const i=B(Bt),r={};for(let e of t)r[e]=Nt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:jt._bundleEnv,_useSimd:jt._useSimd,_useMLBackend:jt._useMLBackend};let a=new f;if(e){s.needLoadCore=!0;let t=i[`${jt._bundleEnv.toLowerCase()}Bundle`]+jt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),xt=new Worker(t),xt.onerror=t=>{let e=new Error(t.message);a.reject(e)},xt.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":Dt&&Dt(e.message);break;case"task":try{At[n](r),delete At[n]}catch(t){throw delete At[n],t}break;case"event":try{At[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!Dt,s.bd=Mt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await Tt("core");let h=Ot++;At[h]=t=>{if(t.success)Object.assign(Pt,t.versions),"{}"!==JSON.stringify(t.versions)&&(jt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},xt.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:rt,worker:st,getUserMedia:ot,camera:await at(),browser:it.browser,version:it.version,OS:it.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Rt();At[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)}},xt.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.0.60-dev-20250812165815(Worker: ${Pt.core&&Pt.core.worker||"Not Loaded"}, Wasm: ${Pt.core&&Pt.core.wasm||"Not Loaded"})`}static enableLogging(){nt._onLog=console.log,jt._onLog=console.log}static disableLogging(){nt._onLog=null,jt._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"cfd",id:n,body:{count:t}})})}}jt._bSupportDce4Module=-1,jt._bSupportIRTModule=-1,jt._versions=null,jt._bundleEnv="DCV",jt._useMLBackend=!1,jt._useSimd=!0,jt.browserInfo=it;var Ut=Object.freeze({__proto__:null,CoreModule:jt,get EnumBufferOverflowProtectionMode(){return p},get EnumCapturedResultItemType(){return ht},get EnumColourChannelUsageType(){return _},get EnumCornerType(){return lt},get EnumCrossVerificationStatus(){return pt},get EnumErrorCode(){return ct},get EnumGrayscaleEnhancementMode(){return ut},get EnumGrayscaleTransformationMode(){return dt},get EnumImageCaptureDistanceMode(){return Et},get EnumImageFileFormat(){return wt},get EnumImagePixelFormat(){return v},get EnumImageTagType(){return ft},EnumIntermediateResultUnitType:_t,get EnumModuleName(){return Ct},get EnumPDFReadingMode(){return gt},get EnumRasterDataSource(){return mt},get EnumRegionObjectElementType(){return vt},get EnumSectionType(){return yt},get EnumTransformMatrixType(){return St},ImageSourceAdapter:nt,_getNorImageData:G,_saveToFile:j,_toBlob:V,_toCanvas:U,_toImage:(t,e)=>{O(e)&&(e=G(e));const i=U(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},get bDebug(){return Mt},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:N,doOrWaitAsyncDependency:It,getNextTaskID:Rt,handleEngineResourcePaths:B,innerVersions:Pt,isArc:t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.radius)||t.radius<0||!T(t.startAngle)||!T(t.endAngle)),isContour:t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),isDSImageData:O,isDSRect:R,isImageTag:A,isLineSegment:D,isObject:I,isOriginalDsImageData:t=>!(!x(t)||!T(t.bytes.length)&&!T(t.bytes.ptr)),isPoint:L,isPolygon:M,isQuad:F,isRect:P,isSimdSupported:async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),mapAsyncDependency:bt,mapPackageRegister:kt,mapTaskCallBack:At,get onLog(){return Dt},productNameMap:W,requestResource:k,setBDebug:Ft,setOnLog:Lt,waitAsyncDependency:Tt,get worker(){return xt},workerAutoResources:Nt}),Vt={license:"",scanMode:t.EnumScanMode.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:jt.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:o,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Gt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Wt=(async()=>{})().constructor;class Yt extends Wt{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,Gt(t)?e=t:"function"==typeof t&&(e=new Wt(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&&(Gt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Ht(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 Xt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const zt=t=>t&&"object"==typeof t&&"function"==typeof t.then,qt=(async()=>{})().constructor;let Kt=class extends qt{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,zt(t)?e=t:"function"==typeof t&&(e=new qt(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&&(zt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},Zt=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=Rt();At[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)}},xt.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=Rt();At[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)}},xt.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var Jt={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1,onProcessedDocumentResultReceived:!1};const $t=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])};let Qt=class{constructor(t){this._irrRegistryState=Jt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),$t(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=Rt();At[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},xt.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),$t(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const te="undefined"==typeof self,ee="function"==typeof importScripts,ie=(()=>{if(!ee){if(!te&&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"./"}})(),ne=t=>{if(null==t&&(t="./"),te||ee);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var re;jt.engineResourcePaths.cvr={version:"3.0.60-dev-20250812165839",path:ie,isInternal:!0},Nt.cvr={js:!0,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING,Ct.MN_DYNAMSOFT_NEURAL_NETWORK]},Nt.dnn={wasm:!0,deps:[Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},kt.cvr={};const se="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,se)<0&&(jt.engineResourcePaths.std={version:se,path:ne(ie+`../../dynamsoft-capture-vision-std@${se}/dist/`),isInternal:!0});const oe="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,oe)<0)&&(jt.engineResourcePaths.dip={version:oe,path:ne(ie+`../../dynamsoft-image-processing@${oe}/dist/`),isInternal:!0});const ae="2.0.10";(!jt.engineResourcePaths.dnn||"string"!=typeof jt.engineResourcePaths.dnn&&N(jt.engineResourcePaths.dnn.version,ae)<0)&&(jt.engineResourcePaths.dnn={version:ae,path:ne(ie+`../../dynamsoft-capture-vision-dnn@${ae}/dist/`),isInternal:!0});let he=class{static getVersion(){return this._version}};var le,ce,ue,de,fe,ge,me,pe,_e,ve,ye,we,Ee,Ce,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le;function Me(t,e){if(t&&t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Me(t.referencedItem,e)}}function Fe(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function Pe(t){let e=!1;const i=[ct.EC_UNSUPPORTED_JSON_KEY_WARNING,ct.EC_LICENSE_AUTH_QUOTA_EXCEEDED,ct.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}he._version=`3.0.60-dev-20250812165839(Worker: ${null===(re=Pt.cvr)||void 0===re?void 0:re.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(le||(le={}));const ke={onTaskResultsReceived:()=>{},isFilter:!0};At[-2]=async t=>{Ne.onDataLoadProgressChanged&&Ne.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let Ne=class t{constructor(){ce.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(jt.browserInfo.OS)?2048:4096,this.onCaptureError=null,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,this._dynamsoft=!0,ue.set(this,null),de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,new Set),_e.set(this,new Set),ve.set(this,new Set),ye.set(this,500),we.set(this,0),Ee.set(this,0),Ce.set(this,!1),Se.set(this,!1),be.set(this,!1),Te.set(this,null),Ie.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Ht(this,be,"f")}static async createInstance(e=!0){if(!kt.license)throw Error("The `license` module cannot be found.");await kt.license.dynamsoft(),await jt.loadWasm();const i=new t,n=new Kt;let r=Rt();return At[r]=async t=>{t.success?(i._instanceID=t.instanceID,i._currentSettings=JSON.parse(JSON.parse(t.outputSettings).data),he._version=`3.0.60-dev-20250812165839(Worker: ${Pt.cvr.worker}, Wasm: ${t.version})`,Xt(i,Se,!0,"f"),Xt(i,ge,i.getIntermediateResultManager(),"f"),Xt(i,Se,!1,"f"),n.resolve(i)):Pe({message:t.message,rj:n.reject,stack:t.stack,functionName:"createInstance"})},xt.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendModelBuffer(t,e){return await jt.loadWasm(),await new Promise((i,n)=>{let r=Rt();const s=B(jt.engineResourcePaths);let o;At[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Pe({message:e.errorString?e.errorString:"Append Model Buffer Failed.",rj:n,errorCode:e.errorCode,functionName:"appendModelBuffer"}),i(e)}Pe({message:t.message,rj:n,stack:t.stack,functionName:"appendModelBuffer"})},e?o=e:"DCV"===jt._bundleEnv?o=s.dcvData+"models/":"DBR"===jt._bundleEnv&&(o=s.dbrBundle+"models/"),xt.postMessage({type:"cvr_appendModelBuffer",id:r,body:{modelName:t,path:o}})})}async _singleFrameModeCallback(t){for(let e of Ht(this,pe,"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;for(let t of Ht(this,pe,"f"))t.isDce?t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}):Ht(this,ce,"m",Oe).call(this,t,i)}setInput(t){if(Fe(this),!t)return Ht(this,Te,"f")&&(Ht(this,ge,"f").removeResultReceiver(Ht(this,Te,"f")),Xt(this,Te,null,"f")),Ht(this,Ie,"f")&&(Ht(this,pe,"f").delete(Ht(this,Ie,"f")),Xt(this,Ie,null,"f")),void Xt(this,ue,null,"f");if(Xt(this,ue,t,"f"),t.isCameraEnhancer){Ht(this,ge,"f")&&(Ht(this,ue,"f")._intermediateResultReceiver.isDce=!0,Ht(this,ge,"f").addResultReceiver(Ht(this,ue,"f")._intermediateResultReceiver),Xt(this,Te,Ht(this,ue,"f")._intermediateResultReceiver,"f"));const t=Ht(this,ue,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Ht(this,pe,"f").add(e),Xt(this,Ie,e,"f")}}}getInput(){return Ht(this,ue,"f")}addImageSourceStateListener(t){if(Fe(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Ht(this,_e,"f").add(t)}removeImageSourceStateListener(t){return Fe(this),Ht(this,_e,"f").delete(t)}addResultReceiver(t){if(Fe(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Ht(this,pe,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Fe(this),Ht(this,pe,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Ht(this,pe,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Kt;let i=Rt();return At[i]=async t=>{t.success?e.resolve():Pe({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},xt.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Fe(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Ht(this,ve,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Fe(this),Ht(this,ve,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Ht(this,ge,"f").removeResultReceiver(ke),0===Ht(this,ve,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1},e={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1};return await Ht(this,ce,"m",Re).call(this,t),void await Ht(this,ce,"m",Ae).call(this,e)}for(let t of Ht(this,ve,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(ht.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(ht.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(ht.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(ht.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(ht.CRIT_BARCODE)&&([...Ht(this,ge,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Ht(this,ge,"f").addResultReceiver(ke)),await Ht(this,ce,"m",Re).call(this,t.verificationEnabled),await Ht(this,ce,"m",Ae).call(this,t.duplicateFilterEnabled),await Ht(this,ce,"m",De).call(this,t.duplicateForgetTime)}async startCapturing(e){if(Fe(this),!this._isPauseScan)return;if(!Ht(this,ue,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);const i=await this.containsTask(e);for(let t of Ht(this,ve,"f"))await this.addResultFilter(t);const n=B(jt.engineResourcePaths);return Ht(this,ue,"f").isCameraEnhancer&&(i.includes("ddn")?Ht(this,ue,"f").setPixelFormat(v.IPF_ABGR_8888):Ht(this,ue,"f").setPixelFormat(v.IPF_GRAYSCALED)),void 0!==Ht(this,ue,"f").singleFrameMode&&"disabled"!==Ht(this,ue,"f").singleFrameMode?(this._templateName=e,void Ht(this,ue,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(Ht(this,ue,"f").getColourChannelUsageType()===_.CCUT_AUTO&&Ht(this,ue,"f").setColourChannelUsageType(i.includes("ddn")?_.CCUT_FULL_CHANNEL:_.CCUT_Y_CHANNEL_ONLY),Ht(this,fe,"f")&&Ht(this,fe,"f").isPending?Ht(this,fe,"f"):(Xt(this,fe,new Kt((t,i)=>{if(this.disposed)return;let r=Rt();At[r]=async n=>{Ht(this,fe,"f")&&!Ht(this,fe,"f").isFulfilled&&(n.success?(this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Ht(this,ue,"f").startFetching(),this._loopReadVideo(e),t()},0)):Pe({message:n.message,rj:i,stack:n.stack,functionName:"startCapturing"}))},xt.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:n}})}),"f"),await Ht(this,fe,"f")))}stopCapturing(){Fe(this),Ht(this,ue,"f")&&(Ht(this,ue,"f").isCameraEnhancer&&void 0!==Ht(this,ue,"f").singleFrameMode&&"disabled"!==Ht(this,ue,"f").singleFrameMode?Ht(this,ue,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Ht(this,ce,"m",Le).call(this),Ht(this,ue,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Xt(this,fe,null,"f"),Ht(this,ue,"f").setColourChannelUsageType(_.CCUT_AUTO)))}async containsTask(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));Pe({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},xt.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Xt(this,Ce,!0,"f"),Ht(this,ue,"f").isBufferEmpty())if(Ht(this,ue,"f").hasNextImageToFetch())for(let t of Ht(this,_e,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(le.ISS_BUFFER_EMPTY);else if(!Ht(this,ue,"f").hasNextImageToFetch())for(let t of Ht(this,_e,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(le.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Ht(this,ue,"f").isBufferEmpty()&&Ht(this,ue,"f").isCameraEnhancer)try{Ht(this,ue,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Ht(this,ue,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Ht(this,ue,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Ht(this,ue,"f").isCameraEnhancer&&Ht(this,ue,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Ht(this,ue,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Ht(this,pe,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of Ht(this,pe,"f"))if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}else{for(let t of Ht(this,ve,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onProcessedDocumentResultReceived(n);Ht(this,ce,"m",Oe).call(this,e,n)}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()-i),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,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Ht(this,ue,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Ht(this,ue,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async capture(e,i){let n;if(Fe(this),i||(i=t._defaultTemplate),Xt(this,Ce,!1,"f"),O(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await k(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(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(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,o=Math.max(r,s);o>this.maxImageSideLength?(Xt(this,Ee,this.maxImageSideLength/o,"f"),i=Math.round(r*Ht(this,Ee,"f")),n=Math.round(s*Ht(this,Ee,"f"))):(i=r,n=s),Ht(this,de,"f")||Xt(this,de,document.createElement("canvas"),"f");const a=Ht(this,de,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,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,o=Math.max(r,s);o>this.maxImageSideLength?(Xt(this,Ee,this.maxImageSideLength/o,"f"),i=Math.round(r*Ht(this,Ee,"f")),n=Math.round(s*Ht(this,Ee,"f"))):(i=r,n=s),Ht(this,de,"f")||Xt(this,de,document.createElement("canvas"),"f");const a=Ht(this,de,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Rt();B(jt.engineResourcePaths);const l=new Kt;return At[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;t.hasOwnProperty("_needContinueProcess")&&delete t._needContinueProcess,e.bytes=i.bytes;for(let i of t.items)0!==Ht(this,Ee,"f")&&Me(i,Ht(this,Ee,"f")),i.type===ht.CRIT_ORIGINAL_IMAGE?i.imageData=e:[ht.CRIT_DESKEWED_IMAGE,ht.CRIT_ENHANCED_IMAGE].includes(i.type)?kt.ddn&&kt.ddn.handleDeskewedAndEnhancedImageResultItem(i):i.type===ht.CRIT_PARSED_RESULT&&kt.dcp&&kt.dcp.handleParsedResultItem(i);const n=t.processedDocumentResult;if(n){if(n.deskewedImageResultItems)for(let t=0;t<n.deskewedImageResultItems.length;t++)kt.ddn&&kt.ddn.handleDeskewedAndEnhancedImageResultItem(n.deskewedImageResultItems[t]);if(n.enhancedImageResultItems)for(let t=0;t<n.enhancedImageResultItems.length;t++)kt.ddn&&kt.ddn.handleDeskewedAndEnhancedImageResultItem(n.enhancedImageResultItems[t])}const r=t.parsedResult;if(r)for(let t=0;t<r.parsedResultItems.length;t++)kt.dcp&&kt.dcp.handleParsedResultItem(r.parsedResultItems[t]);Ht(this,ce,"m",xe).call(this,t,e);const s=Date.now();return s-Ht(this,we,"f")>Ht(this,ye,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),Xt(this,we,s,"f")),Xt(this,Ee,0,"f"),l.resolve(t)}catch(i){Pe({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else Pe({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),xt.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Ht(this,Ce,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(Fe(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await k(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Rt();At[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&Pe({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}Pe({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},xt.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return Fe(this),await new Promise((i,n)=>{let r=Rt();At[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Pe({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}Pe({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},xt.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,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(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return Fe(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Pe({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}Pe({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},xt.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return Fe(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&Pe({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}Pe({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},xt.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return Fe(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Rt();At[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&Pe({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}Pe({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},xt.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return Fe(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Pe({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}Pe({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},xt.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return Ht(this,me,"f")||Xt(this,me,new Zt(this),"f"),Ht(this,me,"f")}getIntermediateResultManager(){if(Fe(this),!Ht(this,Se,"f")&&0!==jt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Ht(this,ge,"f")||Xt(this,ge,new Qt(this),"f"),Ht(this,ge,"f")}async parseRequiredResources(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));Pe({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},xt.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){Fe(this),Ht(this,fe,"f")&&this.stopCapturing(),Xt(this,ue,null,"f"),Ht(this,pe,"f").clear(),Ht(this,_e,"f").clear(),Ht(this,ve,"f").clear(),Ht(this,ge,"f")._intermediateResultReceiverSet.clear(),Xt(this,be,!0,"f");let t=Rt();At[t]=t=>{t.success||Pe({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},xt.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Ht(this,ue,"f"),promiseStartScan:Ht(this,fe,"f"),intermediateResultManager:Ht(this,ge,"f"),bufferdItemsManager:Ht(this,me,"f"),resultReceiverSet:Ht(this,pe,"f"),isaStateListenerSet:Ht(this,_e,"f"),resultFilterSet:Ht(this,ve,"f"),compressRate:Ht(this,Ee,"f"),canvas:Ht(this,de,"f"),isScanner:Ht(this,Ce,"f"),innerUseTag:Ht(this,Se,"f"),isDestroyed:Ht(this,be,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}Pe({message:i.message,rj:e,stack:i.stack,functionName:""})},xt.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};ue=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,ce=new WeakSet,xe=function(t,e){const i=t.intermediateResult;if(i){let t=0;for(let n of Ht(this,ge,"f")._intermediateResultReceiverSet){t++;for(let r of i){if(["onTaskResultsReceived","onTargetROIResultsReceived"].includes(r.info.callbackName)){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.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);t===Ht(this,ge,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}t&&t.hasOwnProperty("intermediateResult")&&delete t.intermediateResult},Oe=function(t,e){e.decodedBarcodesResult&&t.onDecodedBarcodesReceived&&t.onDecodedBarcodesReceived(e.decodedBarcodesResult),e.recognizedTextLinesResult&&t.onRecognizedTextLinesReceived&&t.onRecognizedTextLinesReceived(e.recognizedTextLinesResult),e.processedDocumentResult&&t.onProcessedDocumentResultReceived&&t.onProcessedDocumentResultReceived(e.processedDocumentResult),e.parsedResult&&t.onParsedResultsReceived&&t.onParsedResultsReceived(e.parsedResult),t.onCapturedResultReceived&&t.onCapturedResultReceived(e)},Re=async function(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(t.result);Pe({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},xt.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Ae=async function(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(t.result);Pe({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},xt.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},De=async function(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(t.result);Pe({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},xt.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},Le=async function(){let t=Rt();const e=new Kt;return At[t]=async t=>{if(t.success)return e.resolve();Pe({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},xt.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},Ne._defaultTemplate="Default";let Be=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}};var je;!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="ReadSingleBarcode",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"}(je||(je={}));var Ue=Object.freeze({__proto__:null,CaptureVisionRouter:Ne,CaptureVisionRouterModule:he,CapturedResultReceiver:Be,get EnumImageSourceState(){return le},get EnumPresetTemplate(){return je},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=_t.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.onScaledColourImageUnitReceived=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 Ve="undefined"==typeof self,Ge="function"==typeof importScripts,We=(()=>{if(!Ge){if(!Ve&&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"./"}})();jt.engineResourcePaths.dce={version:"4.2.3-dev-20250812165927",path:We,isInternal:!0},Nt.dce={wasm:!1,js:!1},kt.dce={};let Ye,He,Xe,ze,qe;function Ke(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 Ze(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");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"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ye=navigator,He=Ye.userAgent,Xe=Ye.platform,ze=Ye.mediaDevices),function(){if(!Ve){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:Xe,search:"Win"},Mac:{str:Xe},Linux:{str:Xe}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||He,o=r.search||e,a=r.verStr||He,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||He,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=He.indexOf("Windows NT")&&(r="HarmonyOS"),qe={browser:i,version:n,OS:r}}Ve&&(qe={browser:"ssr",version:0,OS:"ssr"})}();const Je="undefined"!=typeof WebAssembly&&He&&!(/Safari/.test(He)&&!/Chrome/.test(He)&&/\(.+\s11_2_([2-6]).*\)/.test(He)),$e=!("undefined"==typeof Worker),Qe=!(!ze||!ze.getUserMedia),ti=async()=>{let t=!1;if(Qe)try{(await ze.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===qe.browser&&qe.version>66||"Safari"===qe.browser&&qe.version>13||"OPR"===qe.browser&&qe.version>43||"Edge"===qe.browser&&qe.version;var ei={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,E,C,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,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,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<r;n++)i[n]&&i[n].call(this,e||{});return this.__eventListeners[t]=i.filter(function(t){return!1!==t}),this},on:function(t,e){if(this.__eventListeners||(this.__eventListeners={}),1===arguments.length)for(var i in t)this.on(i,t[i]);else this.__eventListeners[t]||(this.__eventListeners[t]=[]),this.__eventListeners[t].push(e);return this},once:function(t,i){if(1===arguments.length)for(var n in t)e.call(this,n,t[n]);else e.call(this,t,i);return this},off:function(e,i){if(!this.__eventListeners)return this;if(0===arguments.length)for(e in this.__eventListeners)t.call(this,e);else if(1===arguments.length&&"object"==typeof arguments[0])for(var n in e)t.call(this,n,e[n]);else t.call(this,e,i);return this}}}(),b.Collection={_objects:[],add:function(){if(this._objects.push.apply(this._objects,arguments),this._onObjectAdded)for(var t=0,e=arguments.length;t<e;t++)this._onObjectAdded(arguments[t]);return this.renderOnAddRemove&&this.requestRenderAll(),this},insertAt:function(t,e,i){var n=this._objects;return i?n[e]=t:n.splice(e,0,t),this._onObjectAdded&&this._onObjectAdded(t),this.renderOnAddRemove&&this.requestRenderAll(),this},remove:function(){for(var t,e=this._objects,i=!1,n=0,r=arguments.length;n<r;n++)-1!==(t=e.indexOf(arguments[n]))&&(i=!0,e.splice(t,1),this._onObjectRemoved&&this._onObjectRemoved(arguments[n]));return this.renderOnAddRemove&&i&&this.requestRenderAll(),this},forEachObject:function(t,e){for(var i=this.getObjects(),n=0,r=i.length;n<r;n++)t.call(e,i[n],n,i);return this},getObjects:function(t){return void 0===t?this._objects.concat():this._objects.filter(function(e){return e.type===t})},item:function(t){return this._objects[t]},isEmpty:function(){return 0===this._objects.length},size:function(){return this._objects.length},contains:function(t,e){return this._objects.indexOf(t)>-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,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){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/h){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*a},radiansToDegrees:function(t){return t/a},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),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),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),o=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(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.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 b.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 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;i<t.length;i++)t[i]=b.util.transformPoint(t[i],e);var n=[t[0].x,t[1].x,t[2].x,t[3].x],r=b.util.array.min(n),s=b.util.array.max(n)-r,o=[t[0].y,t[1].y,t[2].y,t[3].y],a=b.util.array.min(o);return{left:r,top:a,width:s,height:b.util.array.max(o)-a}},invertTransform:function(t){var e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0]],n=b.util.transformPoint({x:t[4],y:t[5]},i,!0);return i[4]=-n.x,i[5]=-n.y,i},toFixed:function(t,e){return parseFloat(Number(t).toFixed(e))},parseUnit:function(t,e){var i=/\D{0,2}$/.exec(t),n=parseFloat(t);switch(e||(e=b.Text.DEFAULT_SVG_FONT_SIZE),i[0]){case"mm":return n*b.DPI/25.4;case"cm":return n*b.DPI/2.54;case"in":return n*b.DPI;case"pt":return n*b.DPI/72;case"pc":return n*b.DPI/72*12;case"em":return n*e;default:return n}},falseFunction:function(){return!1},getKlass:function(t,e){return t=b.util.string.camelize(t.charAt(0).toUpperCase()+t.slice(1)),b.util.resolveNamespace(e)[t]},getSvgAttributes:function(t){var e=["instantiated_by_use","style","id","class"];switch(t){case"linearGradient":e=e.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);break;case"radialGradient":e=e.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);break;case"stop":e=e.concat(["offset","stop-color","stop-opacity"])}return e},resolveNamespace:function(t){if(!t)return b;var e,i=t.split("."),r=i.length,s=n||b.window;for(e=0;e<r;++e)s=s[i[e]];return s},loadImage:function(t,e,i,n){if(t){var r=b.util.createImage(),s=function(){e&&e.call(i,r,!1),r=r.onload=r.onerror=null};r.onload=s,r.onerror=function(){b.log("Error loading "+r.src),e&&e.call(i,null,!0),r=r.onload=r.onerror=null},0!==t.indexOf("data")&&null!=n&&(r.crossOrigin=n),"data:image/svg"===t.substring(0,14)&&(r.onload=null,b.util.loadImageInDom(r,s)),r.src=t}else e&&e.call(i,t)},loadImageInDom:function(t,e){var i=b.document.createElement("div");i.style.width=i.style.height="1px",i.style.left=i.style.top="-100%",i.style.position="absolute",i.appendChild(t),b.document.querySelector("body").appendChild(i),t.onload=function(){e(),i.parentNode.removeChild(i),i=null}},enlivenObjects:function(t,e,i,n){var r=[],s=0,o=(t=t||[]).length;function a(){++s===o&&e&&e(r.filter(function(t){return t}))}o?t.forEach(function(t,e){t&&t.type?b.util.getKlass(t.type,i).fromObject(t,function(i,s){s||(r[e]=i),n&&n(t,i,s),a()}):a()}):e&&e(r)},enlivenObjectEnlivables:function(t,e,i){var n=b.Object.ENLIVEN_PROPS.filter(function(e){return!!t[e]});b.util.enlivenObjects(n.map(function(e){return t[e]}),function(t){var r={};n.forEach(function(i,n){r[i]=t[n],e&&(e[i]=t[n])}),i&&i(r)})},enlivenPatterns:function(t,e){function i(){++r===s&&e&&e(n)}var n=[],r=0,s=(t=t||[]).length;s?t.forEach(function(t,e){t&&t.source?new b.Pattern(t,function(t){n[e]=t,i()}):(n[e]=t,i())}):e&&e(n)},groupSVGElements:function(t,e,i){var n;return t&&1===t.length?t[0]:(e&&(e.width&&e.height?e.centerPoint={x:e.width/2,y:e.height/2}:(delete e.width,delete e.height)),n=new b.Group(t,e),void 0!==i&&(n.sourcePath=i),n)},populateWithProperties:function(t,e,i){if(i&&Array.isArray(i))for(var n=0,r=i.length;n<r;n++)i[n]in t&&(e[i[n]]=t[i[n]])},createCanvasElement:function(){return b.document.createElement("canvas")},copyCanvasElement:function(t){var e=b.util.createCanvasElement();return e.width=t.width,e.height=t.height,e.getContext("2d").drawImage(t,0,0),e},toDataURL:function(t,e,i){return t.toDataURL("image/"+e,i)},createImage:function(){return b.document.createElement("img")},multiplyTransformMatrices:function(t,e,i){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]]},qrDecompose:function(t){var e=s(t[1],t[0]),i=o(t[0],2)+o(t[1],2),n=r(i),h=(t[0]*t[3]-t[2]*t[1])/n,l=s(t[0]*t[2]+t[1]*t[3],i);return{angle:e/a,scaleX:n,scaleY:h,skewX:l/a,skewY:0,translateX:t[4],translateY:t[5]}},calcRotateMatrix:function(t){if(!t.angle)return b.iMatrix.concat();var e=b.util.degreesToRadians(t.angle),i=b.util.cos(e),n=b.util.sin(e);return[i,n,-n,i,0,0]},calcDimensionsMatrix:function(t){var e=void 0===t.scaleX?1:t.scaleX,i=void 0===t.scaleY?1:t.scaleY,n=[t.flipX?-e:e,0,0,t.flipY?-i:i,0,0],r=b.util.multiplyTransformMatrices,s=b.util.degreesToRadians;return t.skewX&&(n=r(n,[1,0,Math.tan(s(t.skewX)),1],!0)),t.skewY&&(n=r(n,[1,Math.tan(s(t.skewY)),0,1],!0)),n},composeMatrix:function(t){var e=[1,0,0,1,t.translateX||0,t.translateY||0],i=b.util.multiplyTransformMatrices;return t.angle&&(e=i(e,b.util.calcRotateMatrix(t))),(1!==t.scaleX||1!==t.scaleY||t.skewX||t.skewY||t.flipX||t.flipY)&&(e=i(e,b.util.calcDimensionsMatrix(t))),e},resetObjectTransform:function(t){t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)},saveObjectTransform:function(t){return{scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}},isTransparent:function(t,e,i,n){n>0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r<a&&0!=(s=o.data[r]<=0);r+=4);return o=null,s},parsePreserveAspectRatioAttribute:function(t){var e,i="meet",n=t.split(" ");return n&&n.length&&("meet"!==(i=n.pop())&&"slice"!==i?(e=i,i="meet"):n.length&&(e=n.pop())),{meetOrSlice:i,alignX:"none"!==e?e.slice(1,4):"none",alignY:"none"!==e?e.slice(5,8):"none"}},clearFabricFontCache:function(t){(t=(t||"").toLowerCase())?b.charWidthsCache[t]&&delete b.charWidthsCache[t]:b.charWidthsCache={}},limitDimsByArea:function(t,e){var i=Math.sqrt(e*t),n=Math.floor(e/i);return{x:Math.floor(i),y:n}},capValue:function(t,e,i){return Math.max(t,Math.min(e,i))},findScaleToFit:function(t,e){return Math.min(e.width/t.width,e.height/t.height)},findScaleToCover:function(t,e){return Math.max(e.width/t.width,e.height/t.height)},matrixToSVG:function(t){return"matrix("+t.map(function(t){return b.util.toFixed(t,b.Object.NUM_FRACTION_DIGITS)}).join(" ")+")"},removeTransformFromObject:function(t,e){var i=b.util.invertTransform(e),n=b.util.multiplyTransformMatrices(i,t.calcOwnMatrix());b.util.applyTransformToObject(t,n)},addTransformToObject:function(t,e){b.util.applyTransformToObject(t,b.util.multiplyTransformMatrices(e,t.calcOwnMatrix()))},applyTransformToObject:function(t,e){var i=b.util.qrDecompose(e),n=new b.Point(i.translateX,i.translateY);t.flipX=!1,t.flipY=!1,t.set("scaleX",i.scaleX),t.set("scaleY",i.scaleY),t.skewX=i.skewX,t.skewY=i.skewY,t.angle=i.angle,t.setPositionByOrigin(n,"center","center")},sizeAfterTransform:function(t,e,i){var n=t/2,r=e/2,s=[{x:-n,y:-r},{x:n,y:-r},{x:-n,y:r},{x:n,y:r}],o=b.util.calcDimensionsMatrix(i),a=b.util.makeBoundingBoxFromPoints(s,o);return{x:a.width,y:a.height}},mergeClipPaths:function(t,e){var i=t,n=e;i.inverted&&!n.inverted&&(i=e,n=t),b.util.applyTransformToObject(n,b.util.multiplyTransformMatrices(b.util.invertTransform(i.calcTransformMatrix()),n.calcTransformMatrix()));var r=i.inverted&&n.inverted;return r&&(i.inverted=n.inverted=!1),new b.Group([i],{clipPath:n,inverted:r})}},function(){var t=Array.prototype.join,e={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},i={m:"l",M:"L"};function n(t,e,i,n,r,s,o,a,h,l,c){var u=b.util.cos(t),d=b.util.sin(t),f=b.util.cos(e),g=b.util.sin(e),m=i*r*f-n*s*g+o,p=n*r*f+i*s*g+a;return["C",l+h*(-i*r*d-n*s*u),c+h*(-n*r*d+i*s*u),m+h*(i*r*g+n*s*f),p+h*(n*r*g-i*s*f),m,p]}function r(t,e,i,n){var r=Math.atan2(e,t),s=Math.atan2(n,i);return s>=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.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=(o===a?-1:1)*Math.sqrt(E/(_*y+v*w));var T=C*i*p/s,I=-C*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;k<D;k++)L[k]=n(R,P,d,u,i,s,x,O,F,f,g),f=L[k][5],g=L[k][6],R=P,P+=M;return L}(i[6]-t,i[7]-e,s,o,h,l,a),u=0,d=c.length;u<d;u++)c[u][1]+=t,c[u][2]+=e,c[u][3]+=t,c[u][4]+=e,c[u][5]+=t,c[u][6]+=e;return c}function o(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-e))}function a(t,e,i,n,r,s,o,a){return function(h){var l,c=(l=h)*l*l,u=function(t){return 3*t*t*(1-t)}(h),d=function(t){return 3*t*(1-t)*(1-t)}(h),f=function(t){return(1-t)*(1-t)*(1-t)}(h);return{x:o*c+r*u+i*d+t*f,y:a*c+s*u+n*d+e*f}}}function h(t,e,i,n,r,s,o,a){return function(h){var l=1-h,c=3*l*l*(i-t)+6*l*h*(r-i)+3*h*h*(o-r),u=3*l*l*(n-e)+6*l*h*(s-n)+3*h*h*(a-s);return Math.atan2(u,c)}}function l(t,e,i,n,r,s){return function(o){var a,h=(a=o)*a,l=function(t){return 2*t*(1-t)}(o),c=function(t){return(1-t)*(1-t)}(o);return{x:r*h+i*l+t*c,y:s*h+n*l+e*c}}}function c(t,e,i,n,r,s){return function(o){var a=1-o,h=2*a*(i-t)+2*o*(r-i),l=2*a*(n-e)+2*o*(s-n);return Math.atan2(l,h)}}function u(t,e,i){var n,r,s={x:e,y:i},a=0;for(r=1;r<=100;r+=1)n=t(r/100),a+=o(s.x,s.y,n.x,n.y),s=n;return a}function d(t){for(var e,i,n,r,s=0,d=t.length,f=0,g=0,m=0,p=0,_=[],v=0;v<d;v++){switch(n={x:f,y:g,command:(e=t[v])[0]},e[0]){case"M":n.length=0,m=f=e[1],p=g=e[2];break;case"L":n.length=o(f,g,e[1],e[2]),f=e[1],g=e[2];break;case"C":i=a(f,g,e[1],e[2],e[3],e[4],e[5],e[6]),r=h(f,g,e[1],e[2],e[3],e[4],e[5],e[6]),n.iterator=i,n.angleFinder=r,n.length=u(i,f,g),f=e[5],g=e[6];break;case"Q":i=l(f,g,e[1],e[2],e[3],e[4]),r=c(f,g,e[1],e[2],e[3],e[4]),n.iterator=i,n.angleFinder=r,n.length=u(i,f,g),f=e[3],g=e[4];break;case"Z":case"z":n.destX=m,n.destY=p,n.length=o(f,g,m,p),f=m,g=p}s+=n.length,_.push(n)}return _.push({length:s,x:f,y:g}),_}b.util.joinPath=function(t){return t.map(function(t){return t.join(" ")}).join(" ")},b.util.parsePath=function(t){var n,r,s,o,a,h=[],l=[],c=b.rePathCommand,u="[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?\\s*",d="("+u+")"+b.commaWsp,f="([01])"+b.commaWsp+"?",g=new RegExp(d+"?"+d+"?"+d+f+f+d+"?("+u+")","g");if(!t||!t.match)return h;for(var m,p=0,_=(a=t.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi)).length;p<_;p++){o=(n=a[p]).slice(1).trim(),l.length=0;var v=n.charAt(0);if(m=[v],"a"===v.toLowerCase())for(var y;y=g.exec(o);)for(var w=1;w<y.length;w++)l.push(y[w]);else for(;s=c.exec(o);)l.push(s[0]);w=0;for(var E=l.length;w<E;w++)r=parseFloat(l[w]),isNaN(r)||m.push(r);var C=e[v.toLowerCase()],S=i[v]||v;if(m.length-1>C)for(var T=1,I=m.length;T<I;T+=C)h.push([v].concat(m.slice(T,T+C))),v=S;else h.push(m)}return h},b.util.makePathSimpler=function(t){var e,i,n,r,o,a,h=0,l=0,c=t.length,u=0,d=0,f=[];for(i=0;i<c;++i){switch(n=!1,(e=t[i].slice(0))[0]){case"l":e[0]="L",e[1]+=h,e[2]+=l;case"L":h=e[1],l=e[2];break;case"h":e[1]+=h;case"H":e[0]="L",e[2]=l,h=e[1];break;case"v":e[1]+=l;case"V":e[0]="L",l=e[1],e[1]=h,e[2]=l;break;case"m":e[0]="M",e[1]+=h,e[2]+=l;case"M":h=e[1],l=e[2],u=e[1],d=e[2];break;case"c":e[0]="C",e[1]+=h,e[2]+=l,e[3]+=h,e[4]+=l,e[5]+=h,e[6]+=l;case"C":o=e[3],a=e[4],h=e[5],l=e[6];break;case"s":e[0]="S",e[1]+=h,e[2]+=l,e[3]+=h,e[4]+=l;case"S":"C"===r?(o=2*h-o,a=2*l-a):(o=h,a=l),h=e[3],l=e[4],e[0]="C",e[5]=e[3],e[6]=e[4],e[3]=e[1],e[4]=e[2],e[1]=o,e[2]=a,o=e[3],a=e[4];break;case"q":e[0]="Q",e[1]+=h,e[2]+=l,e[3]+=h,e[4]+=l;case"Q":o=e[1],a=e[2],h=e[3],l=e[4];break;case"t":e[0]="T",e[1]+=h,e[2]+=l;case"T":"Q"===r?(o=2*h-o,a=2*l-a):(o=h,a=l),e[0]="Q",h=e[1],l=e[2],e[1]=o,e[2]=a,e[3]=h,e[4]=l;break;case"a":e[0]="A",e[6]+=h,e[7]+=l;case"A":n=!0,f=f.concat(s(h,l,e)),h=e[6],l=e[7];break;case"z":case"Z":h=u,l=d}n||f.push(e),r=e[0]}return f},b.util.getSmoothPathFromPoints=function(t,e){var i,n=[],r=new b.Point(t[0].x,t[0].y),s=new b.Point(t[1].x,t[1].y),o=t.length,a=1,h=0,l=o>2;for(e=e||0,l&&(a=t[2].x<s.x?-1:t[2].x===s.x?0:1,h=t[2].y<s.y?-1:t[2].y===s.y?0:1),n.push(["M",r.x-a*e,r.y-h*e]),i=1;i<o;i++){if(!r.eq(s)){var c=r.midPointFrom(s);n.push(["Q",r.x,r.y,c.x,c.y])}r=t[i],i+1<t.length&&(s=t[i+1])}return l&&(a=r.x>t[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];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*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,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,O,R=C.length,A=R;R--;)I=(O=1-(f=C[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;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[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n<i.length-2;)e-=i[n].length,n++;var r,s=i[n],a=e/s.length,h=s.command,l=t[n];switch(h){case"M":return{x:s.x,y:s.y,angle:0};case"Z":case"z":return(r=new b.Point(s.x,s.y).lerp(new b.Point(s.destX,s.destY),a)).angle=Math.atan2(s.destY-s.y,s.destX-s.x),r;case"L":return(r=new b.Point(s.x,s.y).lerp(new b.Point(l[1],l[2]),a)).angle=Math.atan2(l[2]-s.y,l[1]-s.x),r;case"C":case"Q":return function(t,e){for(var i,n,r,s=0,a=0,h=t.iterator,l={x:t.x,y:t.y},c=.01,u=t.angleFinder;a<e&&c>1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(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<t.length-1;r+=2)n.x=t[r],n.y=t[r+1],n=b.util.transformPoint(n,e),i[r]=n.x,i[r+1]=n.y;return i})}}(),function(){var t=Array.prototype.slice;function e(t,e,i){if(t&&0!==t.length){var n=t.length-1,r=e?t[n][e]:t[n];if(e)for(;n--;)i(t[n][e],r)&&(r=t[n][e]);else for(;n--;)i(t[n],r)&&(r=t[n]);return r}}b.util.array={fill:function(t,e){for(var i=t.length;i--;)t[i]=e;return t},invoke:function(e,i){for(var n=t.call(arguments,2),r=[],s=0,o=e.length;s<o;s++)r[s]=n.length?e[s][i].apply(e[s],n):e[s][i].call(e[s]);return r},min:function(t,i){return e(t,i,function(t,e){return t<e})},max:function(t,i){return e(t,i,function(t,e){return t>=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;r<s;r++)e[r]=t({},i[r],n)}else if(i&&"object"==typeof i)for(var o in i)"canvas"===o||"group"===o?e[o]=null:i.hasOwnProperty(o)&&(e[o]=t({},i[o],n));else e=i;else for(var o in i)e[o]=i[o];return e}b.util.object={extend:t,clone:function(e,i){return t({},e,i)}},b.util.object.extend(b.util,b.Observable)}(),function(){function t(t,e){var i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)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,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n<e.length;n++)!1!==(i=t(e,n))&&r.push(i);return r}}}(),function(){var t=Array.prototype.slice,e=function(){},i=function(){for(var t in{toString:1})if("toString"===t)return!1;return!0}(),n=function(t,e,n){for(var r in e)r in t.prototype&&"function"==typeof t.prototype[r]&&(e[r]+"").indexOf("callSuper")>-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,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h<l;h++)n(a,o[h],i);return a.prototype.initialize||(a.prototype.initialize=e),a.prototype.constructor=a,a.prototype.callSuper=s,a}}(),l=!!b.document.createElement("div").attachEvent,c=["touchstart","touchmove","touchend"],b.util.addListener=function(t,e,i,n){t&&t.addEventListener(e,i,!l&&n)},b.util.removeListener=function(t,e,i,n){t&&t.removeEventListener(e,i,!l&&n)},b.util.getPointer=function(t){var e=t.target,i=b.util.getScrollLeftTop(e),n=function(t){var e=t.changedTouches;return e&&e[0]?e[0]:t}(t);return{x:n.clientX+i.left,y:n.clientY+i.top}},b.util.isTouchEvent=function(t){return c.indexOf(t.type)>-1||"touch"===t.pointerType},d="string"==typeof(u=b.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}),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 o(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 a(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=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.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,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=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(o),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)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+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-l,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,!o){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 h()):(d(w,E,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.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(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,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(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t<Math.abs(e)?(t=e,n=i/4):n=0===e&&0===t?i/(2*Math.PI)*Math.asin(1):i/(2*Math.PI)*Math.asin(e/t),{a:t,c:e,p:i,s:n}}function e(t,e,i){return t.a*Math.pow(2,10*(e-=1))*Math.sin((e*i-t.s)*(2*Math.PI)/t.p)}function i(t,e,i,r){return i-n(r-t,0,i,r)+e}function n(t,e,i,n){return(t/=n)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e}b.util.ease={easeInQuad:function(t,e,i,n){return i*(t/=n)*t+e},easeOutQuad:function(t,e,i,n){return-i*(t/=n)*(t-2)+e},easeInOutQuad:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,n){return i*(t/=n)*t*t+e},easeOutCubic:function(t,e,i,n){return i*((t=t/n-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,n){return i*(t/=n)*t*t*t+e},easeOutQuart:function(t,e,i,n){return-i*((t=t/n-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,n){return i*(t/=n)*t*t*t*t+e},easeOutQuint:function(t,e,i,n){return i*((t=t/n-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,n){return(t/=n/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,n){return i*Math.sin(t/n*(Math.PI/2))+e},easeInOutSine:function(t,e,i,n){return-i/2*(Math.cos(Math.PI*t/n)-1)+e},easeInExpo:function(t,e,i,n){return 0===t?e:i*Math.pow(2,10*(t/n-1))+e},easeOutExpo:function(t,e,i,n){return t===n?e+i:i*(1-Math.pow(2,-10*t/n))+e},easeInOutExpo:function(t,e,i,n){return 0===t?e:t===n?e+i:(t/=n/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,n){return-i*(Math.sqrt(1-(t/=n)*t)-1)+e},easeOutCirc:function(t,e,i,n){return i*Math.sqrt(1-(t=t/n-1)*t)+e},easeInOutCirc:function(t,e,i,n){return(t/=n/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(i,n,r,s){var o=0;return 0===i?n:1==(i/=s)?n+r:(o||(o=.3*s),-e(t(r,r,o,1.70158),i,s)+n)},easeOutElastic:function(e,i,n,r){var s=0;if(0===e)return i;if(1==(e/=r))return i+n;s||(s=.3*r);var o=t(n,n,s,1.70158);return o.a*Math.pow(2,-10*e)*Math.sin((e*r-o.s)*(2*Math.PI)/o.p)+o.c+i},easeInOutElastic:function(i,n,r,s){var o=0;if(0===i)return n;if(2==(i/=s/2))return n+r;o||(o=s*(.3*1.5));var a=t(r,r,o,1.70158);return i<1?-.5*e(a,i,s)+n:a.a*Math.pow(2,-10*(i-=1))*Math.sin((i*s-a.s)*(2*Math.PI)/a.p)*.5+a.c+n},easeInBack:function(t,e,i,n,r){return void 0===r&&(r=1.70158),i*(t/=n)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,n,r){return void 0===r&&(r=1.70158),i*((t=t/n-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,n,r){return void 0===r&&(r=1.70158),(t/=n/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:i,easeOutBounce:n,easeInOutBounce:function(t,e,r,s){return t<s/2?.5*i(2*t,0,r,s)+e:.5*n(2*t-s,0,r,s)+.5*r+e}}}(),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.parseUnit,o=e.util.multiplyTransformMatrices,a={cx:"left",x:"left",r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing"},h={stroke:"strokeOpacity",fill:"fillOpacity"},l="font-size",c="clip-path";function u(t){return t in a?a[t]:t}function d(t,i,n,r){var a,h=Array.isArray(i);if("fill"!==t&&"stroke"!==t||"none"!==i){if("strokeUniform"===t)return"non-scaling-stroke"===i;if("strokeDashArray"===t)i="none"===i?null:i.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)i=n&&n.transformMatrix?o(n.transformMatrix,e.parseTransformAttribute(i)):e.parseTransformAttribute(i);else if("visible"===t)i="none"!==i&&"hidden"!==i,n&&!1===n.visible&&(i=!1);else if("opacity"===t)i=parseFloat(i),n&&void 0!==n.opacity&&(i*=n.opacity);else if("textAnchor"===t)i="start"===i?"left":"end"===i?"right":"center";else if("charSpacing"===t)a=s(i,r)/r*1e3;else if("paintFirst"===t){var l=i.indexOf("fill"),c=i.indexOf("stroke");i="fill",(l>-1&&c>-1&&c<l||-1===l&&c>-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r<s;r++)i=e[r],n=t.getElementsByTagName(i),o=o.concat(Array.prototype.slice.call(n));return o}function m(t,e){var i,n=!0;return(i=p(t,e.pop()))&&e.length&&(n=function(t,e){for(var i,n=!0;t.parentNode&&1===t.parentNode.nodeType&&e.length;)n&&(i=e.pop()),n=p(t=t.parentNode,i);return 0===e.length}(t,e)),i&&n&&0===e.length}function p(t,e){var i,n,r=t.nodeName,s=t.getAttribute("class"),o=t.getAttribute("id");if(i=new RegExp("^"+r,"i"),e=e.replace(i,""),o&&e.length&&(i=new RegExp("#"+o+"(?![a-zA-Z\\-]+)","i"),e=e.replace(i,"")),s&&e.length)for(n=(s=s.split(" ")).length;n--;)i=new RegExp("\\."+s[n]+"(?![a-zA-Z\\-]+)","i"),e=e.replace(i,"");return 0===e.length}function _(t,e){var i;if(t.getElementById&&(i=t.getElementById(e)),i)return i;var n,r,s,o=t.getElementsByTagName("*");for(r=0,s=o.length;r<s;r++)if(e===(n=o[r]).getAttribute("id"))return n}e.svgValidTagNamesRegEx=f(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),e.svgViewBoxElementsRegEx=f(["symbol","image","marker","pattern","view","svg"]),e.svgInvalidAncestorsRegEx=f(["pattern","defs","symbol","metadata","clipPath","mask","desc"]),e.svgValidParentsRegEx=f(["symbol","g","a","svg","clipPath","defs"]),e.cssRules={},e.gradientDefs={},e.clipPaths={},e.parseTransformAttribute=function(){function t(t,i,n){t[n]=Math.tan(e.util.degreesToRadians(i[0]))}var i=e.iMatrix,n=e.reNum,r=e.commaWsp,s="(?:(?:(matrix)\\s*\\(\\s*("+n+")"+r+"("+n+")"+r+"("+n+")"+r+"("+n+")"+r+"("+n+")"+r+"("+n+")\\s*\\))|(?:(translate)\\s*\\(\\s*("+n+")(?:"+r+"("+n+"))?\\s*\\))|(?:(scale)\\s*\\(\\s*("+n+")(?:"+r+"("+n+"))?\\s*\\))|(?:(rotate)\\s*\\(\\s*("+n+")(?:"+r+"("+n+")"+r+"("+n+"))?\\s*\\))|(?:(skewX)\\s*\\(\\s*("+n+")\\s*\\))|(?:(skewY)\\s*\\(\\s*("+n+")\\s*\\)))",o=new RegExp("^\\s*(?:(?:"+s+"(?:"+r+"*"+s+")*)?)\\s*$"),a=new RegExp(s,"g");return function(n){var r=i.concat(),h=[];if(!n||n&&!o.test(n))return r;n.replace(a,function(n){var o=new RegExp(s).exec(n).filter(function(t){return!!t}),a=o[1],l=o.slice(2).map(parseFloat);switch(a){case"translate":!function(t,e){t[4]=e[0],2===e.length&&(t[5]=e[1])}(r,l);break;case"rotate":l[0]=e.util.degreesToRadians(l[0]),function(t,i){var n=e.util.cos(i[0]),r=e.util.sin(i[0]),s=0,o=0;3===i.length&&(s=i[1],o=i[2]),t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t[4]=s-(n*s-r*o),t[5]=o-(r*s+n*o)}(r,l);break;case"scale":!function(t,e){var i=e[0],n=2===e.length?e[1]:e[0];t[0]=i,t[3]=n}(r,l);break;case"skewX":t(r,l,2);break;case"skewY":t(r,l,1);break;case"matrix":r=l}h.push(r.concat()),r=i.concat()});for(var l=h[0];h.length>1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();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,o,a,h,l=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")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",S=0,b=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)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),E.minX=i,E.minY=n,E.viewBoxWidth=r,E.viewBoxHeight=o,y?(E.width=r,E.height=o):(E.width=s(d),E.height=s(f),c=E.width/r,u=E.height/o),"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,b=E.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=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)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),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&&n<i.length;){var r=i[n],s=r.getAttribute("xlink:href")||r.getAttribute("href");if(null===s)return;var o,a,h,l,c=s.slice(1),u=r.getAttribute("x")||0,d=r.getAttribute("y")||0,f=_(t,c).cloneNode(!0),m=(f.getAttribute("transform")||"")+" translate("+u+", "+d+")",p=i.length,v=e.svgNS;if(y(f),/^svg$/i.test(f.nodeName)){var w=f.ownerDocument.createElementNS(v,"g");for(a=0,l=(h=f.attributes).length;a<l;a++)o=h.item(a),w.setAttributeNS(v,o.nodeName,o.nodeValue);for(;f.firstChild;)w.appendChild(f.firstChild);f=w}for(a=0,l=(h=r.attributes).length;a<l;a++)"x"!==(o=h.item(a)).nodeName&&"y"!==o.nodeName&&"xlink:href"!==o.nodeName&&"href"!==o.nodeName&&("transform"===o.nodeName?m=o.nodeValue+" "+m:f.setAttribute(o.nodeName,o.nodeValue));f.setAttribute("transform",m),f.setAttribute("instantiated_by_use","1"),f.removeAttribute("id"),r.parentNode.replaceChild(f,r),i.length===p&&n++}}(t);var o,a,h=e.Object.__uid++,l=y(t),c=e.util.toArray(t.getElementsByTagName("*"));if(l.crossOrigin=s&&s.crossOrigin,l.svgUid=h,0===c.length&&e.isLikelyNode){var u=[];for(o=0,a=(c=t.selectNodes('//*[name(.)!="svg"]')).length;o<a;o++)u[o]=c[o];c=u}var d=c.filter(function(t){return y(t),e.svgValidTagNamesRegEx.test(t.nodeName.replace("svg:",""))&&!function(t,e){for(;t&&(t=t.parentNode);)if(t.nodeName&&e.test(t.nodeName.replace("svg:",""))&&!t.getAttribute("instantiated_by_use"))return!0;return!1}(t,e.svgInvalidAncestorsRegEx)});if(!d||d&&!d.length)i&&i([],{});else{var f={};c.filter(function(t){return"clipPath"===t.nodeName.replace("svg:","")}).forEach(function(t){var i=t.getAttribute("id");f[i]=e.util.toArray(t.getElementsByTagName("*")).filter(function(t){return e.svgValidTagNamesRegEx.test(t.nodeName.replace("svg:",""))})}),e.gradientDefs[h]=e.getGradientDefs(t),e.cssRules[h]=e.getCSSRules(t),e.clipPaths[h]=f,e.parseElements(d,function(t,n){i&&(i(t,l,n,c),delete e.gradientDefs[h],delete e.cssRules[h],delete e.clipPaths[h])},n(l),r,s)}}};var E=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+e.reNum+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+e.reNum+"))?\\s+(.*)");i(e,{parseFontDeclaration:function(t,e){var i=t.match(E);if(i){var n=i[1],r=i[3],o=i[4],a=i[5],h=i[6];n&&(e.fontStyle=n),r&&(e.fontWeight=isNaN(parseFloat(r))?r:parseFloat(r)),o&&(e.fontSize=s(o)),h&&(e.fontFamily=h),a&&(e.lineHeight="normal"===a?1:a)}},getGradientDefs:function(t){var e,i=g(t,["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"]),n=0,r={};for(n=i.length;n--;)(e=i[n]).getAttribute("xlink:href")&&w(t,e),r[e.getAttribute("id")]=e;return r},parseAttributes:function(t,n,o){if(t){var a,f,g,p={};void 0===o&&(o=t.getAttribute("svgUid")),t.parentNode&&e.svgValidParentsRegEx.test(t.parentNode.nodeName)&&(p=e.parseAttributes(t.parentNode,n,o));var _=n.reduce(function(e,i){return(a=t.getAttribute(i))&&(e[i]=a),e},{}),v=i(function(t,i){var n={};for(var r in e.cssRules[i])if(m(t,r.split(" ")))for(var s in e.cssRules[i][r])n[s]=e.cssRules[i][r][s];return n}(t,o),e.parseStyleAttribute(t));_=i(_,v),v[c]&&t.setAttribute(c,v[c]),f=g=p.fontSize||e.Text.DEFAULT_SVG_FONT_SIZE,_[l]&&(_[l]=f=s(_[l],g));var y,w,E={};for(var C in _)w=d(y=u(C),_[C],p,f),E[y]=w;E&&E.font&&e.parseFontDeclaration(E.font,E);var S=i(p,E);return e.svgValidParentsRegEx.test(t.nodeName)?S:function(t){for(var i in h)if(void 0!==t[h[i]]&&""!==t[i]){if(void 0===t[i]){if(!e.Object.prototype[i])continue;t[i]=e.Object.prototype[i]}if(0!==t[i].indexOf("url(")){var n=new e.Color(t[i]);t[i]=n.setAlpha(r(n.getAlpha()*t[h[i]],2)).toRgba()}}return t}(S)}},parseElements:function(t,i,n,r,s){new e.ElementsParser(t,i,n,r,s).parse()},parseStyleAttribute:function(t){var e={},i=t.getAttribute("style");return i?("string"==typeof i?function(t,e){var i,n;t.replace(/;\s*$/,"").split(";").forEach(function(t){var r=t.split(":");i=r[0].trim().toLowerCase(),n=r[1].trim(),e[i]=n})}(i,e):function(t,e){var i,n;for(var r in t)void 0!==t[r]&&(i=r.toLowerCase(),n=t[r],e[i]=n)}(i,e),e):e},parsePointsAttribute:function(t){if(!t)return null;var e,i,n=[];for(e=0,i=(t=(t=t.replace(/,/g," ").trim()).split(/\s+/)).length;e<i;e+=2)n.push({x:parseFloat(t[e]),y:parseFloat(t[e+1])});return n},getCSSRules:function(t){var i,n,r=t.getElementsByTagName("style"),s={};for(i=0,n=r.length;i<n;i++){var o=r[i].textContent;""!==(o=o.replace(/\/\*[\s\S]*?\*\//g,"")).trim()&&o.split("}").filter(function(t){return t.trim()}).forEach(function(t){var r=t.split("{"),o={},a=r[1].trim().split(";").filter(function(t){return t.trim()});for(i=0,n=a.length;i<n;i++){var h=a[i].split(":"),l=h[0].trim(),c=h[1].trim();o[l]=c}(t=r[0].trim()).split(",").forEach(function(t){""!==(t=t.replace(/^svg/i,"").trim())&&(s[t]?e.util.object.extend(s[t],o):s[t]=e.util.object.clone(o))})})}return s},loadSVGFromURL:function(t,i,n,r){t=t.replace(/^\n\s*/,"").trim(),new e.util.request(t,{method:"get",onComplete:function(t){var s=t.responseXML;if(!s||!s.documentElement)return i&&i(null),!1;e.parseSVGDocument(s.documentElement,function(t,e,n,r){i&&i(t,e,n,r)},n,r)}})},loadSVGFromString:function(t,i,n,r){var s=(new e.window.DOMParser).parseFromString(t.trim(),"text/xml");e.parseSVGDocument(s.documentElement,function(t,e,n,r){i(t,e,n,r)},n,r)}})}(e),b.ElementsParser=function(t,e,i,n,r,s){this.elements=t,this.callback=e,this.options=i,this.reviver=n,this.svgUid=i&&i.svgUid||0,this.parsingOptions=r,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=s},(p=b.ElementsParser.prototype).parse=function(){this.instances=new Array(this.elements.length),this.numElements=this.elements.length,this.createObjects()},p.createObjects=function(){var t=this;this.elements.forEach(function(e,i){e.setAttribute("svgUid",t.svgUid),t.createObject(e,i)})},p.findTag=function(t){return b[b.util.string.capitalize(t.tagName.replace("svg:",""))]},p.createObject=function(t,e){var i=this.findTag(t);if(i&&i.fromElement)try{i.fromElement(t,this.createCallback(e,t),this.options)}catch(t){b.log(t)}else this.checkIfDone()},p.createCallback=function(t,e){var i=this;return function(n){var r;i.resolveGradient(n,e,"fill"),i.resolveGradient(n,e,"stroke"),n instanceof b.Image&&n._originalElement&&(r=n.parsePreserveAspectRatioAttribute(e)),n._removeTransformMatrix(r),i.resolveClipPath(n,e),i.reviver&&i.reviver(e,n),i.instances[t]=n,i.checkIfDone()}},p.extractPropertyDefinition=function(t,e,i){var n=t[e],r=this.regexUrl;if(r.test(n)){r.lastIndex=0;var s=r.exec(n)[1];return r.lastIndex=0,b[i][this.svgUid][s]}},p.resolveGradient=function(t,e,i){var n=this.extractPropertyDefinition(t,i,"gradientDefs");if(n){var r=e.getAttribute(i+"-opacity"),s=b.Gradient.fromElement(n,t,r,this.options);t.set(i,s)}},p.createClipPathCallback=function(t,e){return function(t){t._removeTransformMatrix(),t.fillRule=t.clipRule,e.push(t)}},p.resolveClipPath=function(t,e){var i,n,r,s,o=this.extractPropertyDefinition(t,"clipPath","clipPaths");if(o){r=[],n=b.util.invertTransform(t.calcTransformMatrix());for(var a=o[0].parentNode,h=e;h.parentNode&&h.getAttribute("clip-path")!==t.clipPath;)h=h.parentNode;h.parentNode.appendChild(a);for(var l=0;l<o.length;l++)i=o[l],this.findTag(i).fromElement(i,this.createClipPathCallback(t,r),this.options);o=1===r.length?r[0]:new b.Group(r),s=b.util.multiplyTransformMatrices(n,o.calcTransformMatrix()),o.clipPath&&this.resolveClipPath(o,h);var c=b.util.qrDecompose(s);o.flipX=!1,o.flipY=!1,o.set("scaleX",c.scaleX),o.set("scaleY",c.scaleY),o.angle=c.angle,o.skewX=c.skewX,o.skewY=0,o.setPositionByOrigin({x:c.translateX,y:c.translateY},"center","center"),t.clipPath=o}else delete t.clipPath},p.checkIfDone=function(){0==--this.numElements&&(this.instances=this.instances.filter(function(t){return null!=t}),this.callback(this.instances,this.elements))},function(t){var e=t.fabric||(t.fabric={});function i(t,e){this.x=t,this.y=e}e.Point?e.warn("fabric.Point is already defined"):(e.Point=i,i.prototype={type:"point",constructor:i,add:function(t){return new i(this.x+t.x,this.y+t.y)},addEquals:function(t){return this.x+=t.x,this.y+=t.y,this},scalarAdd:function(t){return new i(this.x+t,this.y+t)},scalarAddEquals:function(t){return this.x+=t,this.y+=t,this},subtract:function(t){return new i(this.x-t.x,this.y-t.y)},subtractEquals:function(t){return this.x-=t.x,this.y-=t.y,this},scalarSubtract:function(t){return new i(this.x-t,this.y-t)},scalarSubtractEquals:function(t){return this.x-=t,this.y-=t,this},multiply:function(t){return new i(this.x*t,this.y*t)},multiplyEquals:function(t){return this.x*=t,this.y*=t,this},divide:function(t){return new i(this.x/t,this.y/t)},divideEquals:function(t){return this.x/=t,this.y/=t,this},eq:function(t){return this.x===t.x&&this.y===t.y},lt:function(t){return this.x<t.x&&this.y<t.y},lte:function(t){return this.x<=t.x&&this.y<=t.y},gt:function(t){return this.x>t.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 o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a<l;a++)r=n[a],s=n[(a+1)%l],o=i.intersectLineLine(t,e,r,s),h.appendPoints(o.points);return h.points.length>0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n<s;n++){var o=t[n],a=t[(n+1)%s],h=i.intersectLinePolygon(o,a,e);r.appendPoints(h.points)}return r.points.length>0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.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,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i<n?6:0);break;case i:r=(n-t)/l+2;break;case n:r=(t-i)/l+4}r/=6}return[Math.round(360*r),Math.round(100*s),Math.round(100*o)]},getSource:function(){return this._source},setSource:function(t){this._source=t},toRgb:function(){var t=this.getSource();return"rgb("+t[0]+","+t[1]+","+t[2]+")"},toRgba:function(){var t=this.getSource();return"rgba("+t[0]+","+t[1]+","+t[2]+","+t[3]+")"},toHsl:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsl("+e[0]+","+e[1]+"%,"+e[2]+"%)"},toHsla:function(){var t=this.getSource(),e=this._rgbToHsl(t[0],t[1],t[2]);return"hsla("+e[0]+","+e[1]+"%,"+e[2]+"%,"+t[3]+")"},toHex:function(){var t,e,i,n=this.getSource();return t=1===(t=n[0].toString(16)).length?"0"+t:t,e=1===(e=n[1].toString(16)).length?"0"+e:e,i=1===(i=n[2].toString(16)).length?"0"+i:i,t.toUpperCase()+e.toUpperCase()+i.toUpperCase()},toHexa:function(){var t,e=this.getSource();return t=1===(t=(t=Math.round(255*e[3])).toString(16)).length?"0"+t:t,this.toHex()+t.toUpperCase()},getAlpha:function(){return this.getSource()[3]},setAlpha:function(t){var e=this.getSource();return e[3]=t,this.setSource(e),this},toGrayscale:function(){var t=this.getSource(),e=parseInt((.3*t[0]+.59*t[1]+.11*t[2]).toFixed(0),10),i=t[3];return this.setSource([e,e,e,i]),this},toBlackWhite:function(t){var e=this.getSource(),i=(.3*e[0]+.59*e[1]+.11*e[2]).toFixed(0),n=e[3];return t=t||127,i=Number(i)<Number(t)?0:255,this.setSource([i,i,i,n]),this},overlayWith:function(t){t instanceof i||(t=new i(t));var e,n=[],r=this.getAlpha(),s=this.getSource(),o=t.getSource();for(e=0;e<3;e++)n.push(Math.round(.5*s[e]+.5*o[e]));return n[3]=r,this.setSource(n),this}},e.Color.reRGBa=/^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/i,e.Color.reHSLa=/^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/i,e.Color.reHex=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,e.Color.colorNameMap={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#00FFFF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blue:"#0000FF",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#FF00FF",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#00FF00",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#663399",red:"#FF0000",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFFFFF",whitesmoke:"#F5F5F5",yellow:"#FFFF00",yellowgreen:"#9ACD32"},e.Color.fromRgb=function(t){return i.fromSource(i.sourceFromRgb(t))},e.Color.sourceFromRgb=function(t){var e=t.match(i.reRGBa);if(e){var n=parseInt(e[1],10)/(/%$/.test(e[1])?100:1)*(/%$/.test(e[1])?255:1),r=parseInt(e[2],10)/(/%$/.test(e[2])?100:1)*(/%$/.test(e[2])?255:1),s=parseInt(e[3],10)/(/%$/.test(e[3])?100:1)*(/%$/.test(e[3])?255:1);return[parseInt(n,10),parseInt(r,10),parseInt(s,10),e[4]?parseFloat(e[4]):1]}},e.Color.fromRgba=i.fromRgb,e.Color.fromHsl=function(t){return i.fromSource(i.sourceFromHsl(t))},e.Color.sourceFromHsl=function(t){var e=t.match(i.reHSLa);if(e){var r,s,o,a=(parseFloat(e[1])%360+360)%360/360,h=parseFloat(e[2])/(/%$/.test(e[2])?100:1),l=parseFloat(e[3])/(/%$/.test(e[3])?100:1);if(0===h)r=s=o=l;else{var c=l<=.5?l*(h+1):l+h-l*h,u=2*l-c;r=n(u,c,a+1/3),s=n(u,c,a),o=n(u,c,a-1/3)}return[Math.round(255*r),Math.round(255*s),Math.round(255*o),e[4]?parseFloat(e[4]):1]}},e.Color.fromHsla=i.fromHsl,e.Color.fromHex=function(t){return i.fromSource(i.sourceFromHex(t))},e.Color.sourceFromHex=function(t){if(t.match(i.reHex)){var e=t.slice(t.indexOf("#")+1),n=3===e.length||4===e.length,r=8===e.length||4===e.length,s=n?e.charAt(0)+e.charAt(0):e.substring(0,2),o=n?e.charAt(1)+e.charAt(1):e.substring(2,4),a=n?e.charAt(2)+e.charAt(2):e.substring(4,6),h=r?n?e.charAt(3)+e.charAt(3):e.substring(6,8):"FF";return[parseInt(s,16),parseInt(o,16),parseInt(a,16),parseFloat((parseInt(h,16)/255).toFixed(2))]}},e.Color.fromSource=function(t){var e=new i;return e.setSource(t),e})}(e),function(t){var e=t.fabric||(t.fabric={}),i=["e","se","s","sw","w","nw","n","ne","e"],n=["ns","nesw","ew","nwse"],r={},s="left",o="top",a="right",h="bottom",l="center",c={top:h,bottom:o,left:a,right:s,center:l},u=e.util.radiansToDegrees,d=Math.sign||function(t){return(t>0)-(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===l&&t.originY===l}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,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function E(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.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 b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),C(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),C(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,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)o=e.scaleX*S,a=e.scaleY*S;else{if(s=E(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),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 o=f(n,e);return i[o]+"-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,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+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)<f?c=m:Math.abs(c-g)<f&&(c=g)}return c<0&&(c=360+c),c%=360,a=s.angle!==c,s.angle=c,a})),r.scalingEqually=w("scaling",y(function(t,e,i,n){return I(t,e,i,n)})),r.scalingX=w("scaling",y(function(t,e,i,n){return I(t,e,i,n,{by:"x"})})),r.scalingY=w("scaling",y(function(t,e,i,n){return I(t,e,i,n,{by:"y"})})),r.scalingYOrSkewingX=function(t,e,i,n){return t[e.target.canvas.altActionKey]?r.skewHandlerX(t,e,i,n):r.scalingY(t,e,i,n)},r.scalingXOrSkewingY=function(t,e,i,n){return t[e.target.canvas.altActionKey]?r.skewHandlerY(t,e,i,n):r.scalingX(t,e,i,n)},r.changeWidth=w("resizing",y(function(t,e,i,n){var r=e.target,s=E(e,e.originX,e.originY,i,n),o=r.strokeWidth/(r.strokeUniform?r.scaleX:1),a=p(e)?2:1,h=r.width,l=Math.abs(s.x*a/r.scaleX)-o;return r.set("width",Math.max(l,0)),h!==l})),r.skewHandlerX=function(t,e,i,n){var r,h=e.target,c=h.skewX,u=e.originY;return!h.lockSkewingX&&(0===c?r=E(e,l,l,i,n).x>0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),C(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=E(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),C(a)&&(r=r===o?h:o)),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,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},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,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/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[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),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 o,a,h,l,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);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},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,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[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 b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,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,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.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,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["<linearGradient ",o,' x1="',a.x1,'" y1="',a.y1,'" x2="',a.x2,'" y2="',a.y2,'">\n']:"radial"===this.type&&(s=["<radialGradient ",o,' cx="',l?a.x1:a.x2,'" cy="',l?a.y1:a.y2,'" r="',l?a.r1:a.r2,'" fx="',l?a.x2:a.x1,'" fy="',l?a.y2:a.y1,'">\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n<r;n++)h[n].offset=1-h[n].offset;var m=Math.min(a.r1,a.r2);if(m>0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n<r;n++)h[n].offset+=p*(1-h[n].offset)}}for(n=0,r=h.length;n<r;n++){var _=h[n];s.push("<stop ",'offset="',100*_.offset+"%",'" style="stop-color:',_.color,void 0!==_.opacity?";stop-opacity: "+_.opacity:";",'"/>\n')}return s.push("linear"===this.type?"</linearGradient>\n":"</radialGradient>\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;i<n;i++){var s=this.colorStops[i].color,o=this.colorStops[i].opacity,a=this.colorStops[i].offset;void 0!==o&&(s=new b.Color(s).setAlpha(o).toRgba()),e.addColorStop(a,s)}return e}}}),b.util.object.extend(b.Gradient,{fromElement:function(e,i,n,r){var s=parseFloat(n)/(/%$/.test(n)?100:1);s=s<0?0:s>1?1:s,isNaN(s)&&(s=1);var o,a,h,l,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?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=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)),h=c.length;h--;)f.push(t(c[h],s));return l=b.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,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,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,o="";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?o=e.src:e.toDataURL&&(o=e.toDataURL()),'<pattern id="SVGID_'+this.id+'" x="'+r+'" y="'+s+'" width="'+i+'" height="'+n+'">\n<image x="0" y="0" width="'+e.width+'" height="'+e.height+'" xlink:href="'+o+'"></image>\n</pattern>\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,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'<filter id="SVGID_'+this.id+'" y="-'+r+'%" height="'+(100+2*r)+'%" x="-'+n+'%" width="'+(100+2*n)+'%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="'+i(this.blur?this.blur/2:0,s)+'"></feGaussianBlur>\n\t<feOffset dx="'+i(o.x,s)+'" dy="'+i(o.y,s)+'" result="oBlur" ></feOffset>\n\t<feFlood flood-color="'+a.toRgb()+'" flood-opacity="'+a.getAlpha()+'"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\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,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=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=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;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,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i<n;i++)(e=this._objects[i]).group||e.setCoords(!0);return r&&r.setCoords(),s&&s.setCoords(!0),o&&o.setCoords(!0),this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll(),this},zoomToPoint:function(t,e){var i=t,n=this.viewportTransform.slice(0);t=r(t,s(this.viewportTransform)),n[0]=e,n[3]=e;var o=r(t,n);return n[4]+=i.x-o.x,n[5]+=i.y-o.y,this.setViewportTransform(n)},setZoom:function(t){return this.zoomToPoint(new b.Point(0,0),t),this},absolutePan:function(t){var e=this.viewportTransform.slice(0);return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)},relativePan:function(t){return this.absolutePan(new b.Point(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))},getElement:function(){return this.lowerCanvasEl},_onObjectAdded:function(t){this.stateful&&t.setupState(),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added")},_onObjectRemoved:function(t){this.fire("object:removed",{target:t}),t.fire("removed"),delete t.canvas},clearContext:function(t){return t.clearRect(0,0,this.width,this.height),this},getContext:function(){return this.contextContainer},clear:function(){return this.remove.apply(this,this.getObjects()),this.backgroundImage=null,this.overlayImage=null,this.backgroundColor="",this.overlayColor="",this._hasITextHandlers&&(this.off("mouse:up",this._mouseUpITextHandler),this._iTextInstances=null,this._hasITextHandlers=!1),this.clearContext(this.contextContainer),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll(),this},renderAll:function(){var t=this.contextContainer;return this.renderCanvas(t,this._objects),this},renderAndReset:function(){this.isRendering=0,this.renderAll()},requestRenderAll:function(){return this.isRendering||(this.isRendering=b.util.requestAnimFrame(this.renderAndResetBound)),this},calcViewportBoundaries:function(){var t={},e=this.width,i=this.height,n=s(this.viewportTransform);return t.tl=r({x:0,y:0},n),t.br=r({x:e,y:i},n),t.tr=new b.Point(t.br.x,t.tl.y),t.bl=new b.Point(t.tl.x,t.br.y),this.vptCoords=t,t},cancelRequestedRender:function(){this.isRendering&&(b.util.cancelAnimFrame(this.isRendering),this.isRendering=0)},renderCanvas:function(t,e){var i=this.viewportTransform,n=this.clipPath;this.cancelRequestedRender(),this.calcViewportBoundaries(),this.clearContext(t),b.util.setImageSmoothing(t,this.imageSmoothingEnabled),this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),!this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),n&&(n.canvas=this,n.shouldCache(),n._transformDone=!0,n.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t)),this._renderOverlay(t),this.controlsAboveOverlay&&this.interactive&&this.drawControls(t),this.fire("after:render",{ctx:t})},drawClipPathOnCanvas:function(t){var e=this.viewportTransform,i=this.clipPath;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5]),t.globalCompositeOperation="destination-in",i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},_renderObjects:function(t,e){var i,n;for(i=0,n=e.length;i<n;++i)e[i]&&e[i].render(t)},_renderBackgroundOrOverlay:function(t,e){var i=this[e+"Color"],n=this[e+"Image"],r=this.viewportTransform,s=this[e+"Vpt"];if(i||n){if(i){t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=i.toLive?i.toLive(t,this):i,s&&t.transform(r[0],r[1],r[2],r[3],r[4],r[5]),t.transform(1,0,0,1,i.offsetX||0,i.offsetY||0);var o=i.gradientTransform||i.patternTransform;o&&t.transform(o[0],o[1],o[2],o[3],o[4],o[5]),t.fill(),t.restore()}n&&(t.save(),s&&t.transform(r[0],r[1],r[2],r[3],r[4],r[5]),n.render(t),t.restore())}},_renderBackground:function(t){this._renderBackgroundOrOverlay(t,"background")},_renderOverlay:function(t){this._renderBackgroundOrOverlay(t,"overlay")},getCenter:function(){return{top:this.height/2,left:this.width/2}},getCenterPoint:function(){return new b.Point(this.width/2,this.height/2)},centerObjectH:function(t){return this._centerObject(t,new b.Point(this.getCenterPoint().x,t.getCenterPoint().y))},centerObjectV:function(t){return this._centerObject(t,new b.Point(t.getCenterPoint().x,this.getCenterPoint().y))},centerObject:function(t){var e=this.getCenterPoint();return this._centerObject(t,e)},viewportCenterObject:function(t){var e=this.getVpCenter();return this._centerObject(t,e)},viewportCenterObjectH:function(t){var e=this.getVpCenter();return this._centerObject(t,new b.Point(e.x,t.getCenterPoint().y)),this},viewportCenterObjectV:function(t){var e=this.getVpCenter();return this._centerObject(t,new b.Point(t.getCenterPoint().x,e.y))},getVpCenter:function(){var t=this.getCenterPoint(),e=s(this.viewportTransform);return r(t,e)},_centerObject:function(t,e){return t.setPositionByOrigin(e,"center","center"),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll(),this},toDatalessJSON:function(t){return this.toDatalessObject(t)},toObject:function(t){return this._toObjectMethod("toObject",t)},toDatalessObject:function(t){return this._toObjectMethod("toDatalessObject",t)},_toObjectMethod:function(e,i){var n=this.clipPath,r={version:b.version,objects:this._toObjects(e,i)};return n&&!n.excludeFromExport&&(r.clipPath=this._toObject(this.clipPath,e,i)),t(r,this.__serializeBgOverlay(e,i)),b.util.populateWithProperties(this,r,i),r},_toObjects:function(t,e){return this._objects.filter(function(t){return!t.excludeFromExport}).map(function(i){return this._toObject(i,t,e)},this)},_toObject:function(t,e,i){var n;this.includeDefaultValues||(n=t.includeDefaultValues,t.includeDefaultValues=!1);var r=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=n),r},__serializeBgOverlay:function(t,e){var i={},n=this.backgroundImage,r=this.overlayImage,s=this.backgroundColor,o=this.overlayColor;return s&&s.toObject?s.excludeFromExport||(i.background=s.toObject(e)):s&&(i.background=s),o&&o.toObject?o.excludeFromExport||(i.overlay=o.toObject(e)):o&&(i.overlay=o),n&&!n.excludeFromExport&&(i.backgroundImage=this._toObject(n,t,e)),r&&!r.excludeFromExport&&(i.overlayImage=this._toObject(r,t,e)),i},svgViewportTransformation:!0,toSVG:function(t,e){t||(t={}),t.reviver=e;var i=[];return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push('<g clip-path="url(#'+this.clipPath.clipPathId+')" >\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("</g>\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push("</svg>"),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',r,'" ','height="',s,'" ',o,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",b.version,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"</defs>\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'<clipPath id="'+e.clipPathId+'" >\n'+this.clipPath.toClipPathSVG(t.reviver)+"</clipPath>\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,o,a,h="",l={},c=b.fontPaths,u=[];for(this._objects.forEach(function t(e){u.push(e),e._objects&&e._objects.forEach(t)}),o=0,a=u.length;o<a;o++)if(e=(t=u[o]).fontFamily,-1!==t.type.indexOf("text")&&!l[e]&&c[e]&&(l[e]=!0,t.styles))for(r in i=t.styles)for(s in n=i[r])!l[e=n[s].fontFamily]&&c[e]&&(l[e]=!0);for(var d in l)h+=["\t\t@font-face {\n","\t\t\tfont-family: '",d,"';\n","\t\t\tsrc: url('",c[d],"');\n","\t\t}\n"].join("");return h&&(h=['\t<style type="text/css">',"<![CDATA[\n",h,"]]>","</style>\n"].join("")),h},_setSVGObjects:function(t,e){var i,n,r,s=this._objects;for(n=0,r=s.length;n<r;n++)(i=s[n]).excludeFromExport||this._setSVGObject(t,i,e)},_setSVGObject:function(t,e,i){t.push(e.toSVG(i))},_setSVGBgOverlayImage:function(t,e,i){this[e]&&!this[e].excludeFromExport&&this[e].toSVG&&t.push(this[e].toSVG(i))},_setSVGBgOverlayColor:function(t,e){var i=this[e+"Color"],n=this.viewportTransform,r=this.width,s=this.height;if(i)if(i.toLive){var o=i.repeat,a=b.util.invertTransform(n),h=this[e+"Vpt"]?b.util.matrixToSVG(a):"";t.push('<rect transform="'+h+" translate(",r/2,",",s/2,')"',' x="',i.offsetX-r/2,'" y="',i.offsetY-s/2,'" ','width="',"repeat-y"===o||"no-repeat"===o?i.source.width:r,'" height="',"repeat-x"===o||"no-repeat"===o?i.source.height:s,'" fill="url(#SVGID_'+i.id+')"',"></rect>\n")}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',i,'"',"></rect>\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;e<r.length;e++)n=r[e],i(this._objects,n),this._objects.push(n);else i(this._objects,t),this._objects.push(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},sendBackwards:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(a=h._objects,n=0;n<a.length;n++)r=a[n],(s=this._objects.indexOf(r))>0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,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,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))<this._objects.length-1-l&&(o=s+1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else(s=this._objects.indexOf(t))!==this._objects.length-1&&(o=this._findNewUpperIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewUpperIndex:function(t,e,i){var n,r,s;if(i){for(n=e,r=e+1,s=this._objects.length;r<s;++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},moveTo:function(t,e){return i(this._objects,t),this._objects.splice(e,0,t),this.renderOnAddRemove&&this.requestRenderAll()},dispose:function(){return this.isRendering&&(b.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"),b.util.setStyle(this.lowerCanvasEl,this._originalCanvasStyle),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),b.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},toString:function(){return"#<fabric.Canvas ("+this.complexity()+"): { objects: "+this._objects.length+" }>"}}),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=a();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=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(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<i;e++)this._drawSegment(t,n,r),n=this._points[e],r=this._points[e+1];t.lineTo(n.x,n.y),t.stroke(),t.restore()},convertPointsToSVGPath:function(t){var e=this.width/1e3;return b.util.getSmoothPathFromPoints(t,e)},_isEmptySVGPath:function(t){return"M 0 0 Q 0 0 0 0 L 0 0"===b.util.joinPath(t)},createPath:function(t){var e=new b.Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new b.Shadow(this.shadow)),e},decimatePoints:function(t,e){if(t.length<=2)return t;var i,n=this.canvas.getZoom(),r=Math.pow(e/n,2),s=t.length-1,o=t[0],a=[o];for(i=1;i<s-1;i++)Math.pow(o.x-t[i].x,2)+Math.pow(o.y-t[i].y,2)>=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_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;t<e;t++)this.dot(i,n[t]);i.restore()},onMouseMove:function(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.needsFullRender()?(this.canvas.clearContext(this.canvas.contextTop),this.addPoint(t),this._render()):this.drawDot(t))},onMouseUp:function(){var t,e,i=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;var n=[];for(t=0,e=this.points.length;t<e;t++){var r=this.points[t],s=new b.Circle({radius:r.radius,left:r.x,top:r.y,originX:"center",originY:"center",fill:r.fill});this.shadow&&(s.shadow=new b.Shadow(this.shadow)),n.push(s)}var o=new b.Group(n);o.canvas=this.canvas,this.canvas.fire("before:path:created",{path:o}),this.canvas.add(o),this.canvas.fire("path:created",{path:o}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=i,this.canvas.requestRenderAll()},addPoint:function(t){var e=new b.Point(t.x,t.y),i=b.util.getRandomInt(Math.max(0,this.width-20),this.width+20)/2,n=new b.Color(this.color).setAlpha(b.util.getRandomInt(0,100)/100).toRgba();return e.radius=i,e.fill=n,this.points.push(e),e}}),b.SprayBrush=b.util.createClass(b.BaseBrush,{width:10,density:20,dotWidth:1,dotWidthVariance:1,randomOpacity:!1,optimizeOverlapping:!0,initialize:function(t){this.canvas=t,this.sprayChunks=[]},onMouseDown:function(t){this.sprayChunks.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.render(this.sprayChunkPoints)},onMouseMove:function(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.addSprayChunk(t),this.render(this.sprayChunkPoints))},onMouseUp:function(){var t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;for(var e=[],i=0,n=this.sprayChunks.length;i<n;i++)for(var r=this.sprayChunks[i],s=0,o=r.length;s<o;s++){var a=new b.Rect({width:r[s].width,height:r[s].width,left:r[s].x+1,top:r[s].y+1,originX:"center",originY:"center",fill:this.color});e.push(a)}this.optimizeOverlapping&&(e=this._getOptimizedRects(e));var h=new b.Group(e);this.shadow&&h.set("shadow",new b.Shadow(this.shadow)),this.canvas.fire("before:path:created",{path:h}),this.canvas.add(h),this.canvas.fire("path:created",{path:h}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()},_getOptimizedRects:function(t){var e,i,n,r={};for(i=0,n=t.length;i<n;i++)r[e=t[i].left+""+t[i].top]||(r[e]=t[i]);var s=[];for(e in r)s.push(r[e]);return s},render:function(t){var e,i,n=this.canvas.contextTop;for(n.fillStyle=this.color,this._saveAndTransform(n),e=0,i=t.length;e<i;e++){var r=t[e];void 0!==r.opacity&&(n.globalAlpha=r.opacity),n.fillRect(r.x,r.y,r.width,r.width)}n.restore()},_render:function(){var t,e,i=this.canvas.contextTop;for(i.fillStyle=this.color,this._saveAndTransform(i),t=0,e=this.sprayChunks.length;t<e;t++)this.render(this.sprayChunks[t]);i.restore()},addSprayChunk:function(t){this.sprayChunkPoints=[];var e,i,n,r,s=this.width/2;for(r=0;r<this.density;r++){e=b.util.getRandomInt(t.x-s,t.x+s),i=b.util.getRandomInt(t.y-s,t.y+s),n=this.dotWidthVariance?b.util.getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth;var o=new b.Point(e,i);o.width=n,this.randomOpacity&&(o.opacity=b.util.getRandomInt(0,100)/100),this.sprayChunkPoints.push(o)}this.sprayChunks.push(this.sprayChunkPoints)}}),b.PatternBrush=b.util.createClass(b.PencilBrush,{getPatternSrc:function(){var t=b.util.createCanvasElement(),e=t.getContext("2d");return t.width=t.height=25,e.fillStyle=this.color,e.beginPath(),e.arc(10,10,10,0,2*Math.PI,!1),e.closePath(),e.fill(),t},getPatternSrcFunction:function(){return String(this.getPatternSrc).replace("this.color",'"'+this.color+'"')},getPattern:function(t){return t.createPattern(this.source||this.getPatternSrc(),"repeat")},_setBrushStyles:function(t){this.callSuper("_setBrushStyles",t),t.strokeStyle=this.getPattern(t)},createPath:function(t){var e=this.callSuper("createPath",t),i=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new b.Pattern({source:this.source||this.getPatternSrcFunction(),offsetX:-i.x,offsetY:-i.y}),e}}),function(){var t=b.util.getPointer,e=b.util.degreesToRadians,i=b.util.isTouchEvent;for(var n in b.Canvas=b.util.createClass(b.StaticCanvas,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e),this._initInteractive(),this._createCacheCanvas()},uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",interactive:!0,selection:!0,selectionKey:"shiftKey",altSelectionKey:null,selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",containerClass:"canvas-container",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,isDrawingMode:!1,preserveObjectStacking:!1,snapAngle:0,snapThreshold:null,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,targets:[],enablePointerEvents:!1,_hoveredTarget:null,_hoveredTargets:[],_initInteractive:function(){this._currentTransform=null,this._groupSelector=null,this._initWrapperElement(),this._createUpperCanvas(),this._initEventListeners(),this._initRetinaScaling(),this.freeDrawingBrush=b.PencilBrush&&new b.PencilBrush(this),this.calcOffset()},_chooseObjectsToRender:function(){var t,e,i,n=this.getActiveObjects();if(n.length>0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r<s;r++)t=this._objects[r],-1===n.indexOf(t)?e.push(t):i.push(t);n.length>1&&(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 o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,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,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,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:l.x,originY:l.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,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,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),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,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],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,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,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{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: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){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,o=!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,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=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[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||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;s<n.length;s++)n[s].fire(t,r);return i},_handleEvent:function(t,e,i,n){var r=this._target,s=this.targets||[],o={e:t,target:r,subTargets:s,button:i||1,isClick:n||!1,pointer:this._pointer,absolutePointer:this._absolutePointer,transform:this._currentTransform};"up"===e&&(o.currentTarget=this.findTarget(t),o.currentSubTargets=this.targets),this.fire("mouse:"+e,o),r&&r.fire("mouse"+e,o);for(var a=0;a<s.length;a++)s[a].fire("mouse"+e,o)},_finalizeCurrentTransform:function(t){var e=this._currentTransform,i=e.target,n={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),(e.actionPerformed||this.stateful&&i.hasStateChanged())&&this._fire("modified",n)},_onMouseDownInDrawingMode:function(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&this.discardActiveObject(t).requestRenderAll();var e=this.getPointer(t);this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down")},_onMouseMoveInDrawingMode:function(t){if(this._isCurrentlyDrawing){var e=this.getPointer(t);this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")},_onMouseUpInDrawingMode:function(t){var e=this.getPointer(t);this._isCurrentlyDrawing=this.freeDrawingBrush.onMouseUp({e:t,pointer:e}),this._handleEvent(t,"up")},__onMouseDown:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"down:before");var e=this._target;if(n(t,3))this.fireRightClick&&this._handleEvent(t,"down",3);else if(n(t,2))this.fireMiddleClick&&this._handleEvent(t,"down",2);else if(this.isDrawingMode)this._onMouseDownInDrawingMode(t);else if(this._isMainEvent(t)&&!this._currentTransform){var i=this._pointer;this._previousPointer=i;var r=this._shouldRender(e),s=this._shouldGroup(t,e);if(this._shouldClearSelection(t,e)?this.discardActiveObject(t):s&&(this._handleGrouping(t,e),e=this._activeObject),!this.selection||e&&(e.selectable||e.isEditing||e===this._activeObject)||(this._groupSelector={ex:this._absolutePointer.x,ey:this._absolutePointer.y,top:0,left:0}),e){var o=e===this._activeObject;e.selectable&&"down"===e.activeOn&&this.setActiveObject(e,t);var a=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t));if(e.__corner=a,e===this._activeObject&&(a||!s)){this._setupCurrentTransform(t,e,o);var h=e.controls[a],l=(i=this.getPointer(t),h&&h.getMouseDownHandler(t,e,h));l&&l(t,this._currentTransform,i.x,i.y)}}this._handleEvent(t,"down"),(r||s)&&this.requestRenderAll()}},_resetTransformEventData:function(){this._target=null,this._pointer=null,this._absolutePointer=null},_cacheTransformEventData:function(t){this._resetTransformEventData(),this._pointer=this.getPointer(t,!0),this._absolutePointer=this.restorePointerVpt(this._pointer),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)||null},_beforeTransform:function(t){var e=this._currentTransform;this.stateful&&e.target.saveState(),this.fire("before:transform",{e:t,transform:e})},__onMouseMove:function(t){var e,i;if(this._handleEvent(t,"move:before"),this._cacheTransformEventData(t),this.isDrawingMode)this._onMouseMoveInDrawingMode(t);else if(this._isMainEvent(t)){var n=this._groupSelector;n?(i=this._absolutePointer,n.left=i.x-n.ex,n.top=i.y-n.ey,this.renderTop()):this._currentTransform?this._transformObject(t):(e=this.findTarget(t)||null,this._setCursorFromEvent(t,e),this._fireOverOutEvents(e,t)),this._handleEvent(t,"move"),this._resetTransformEventData()}},_fireOverOutEvents:function(t,e){var i=this._hoveredTarget,n=this._hoveredTargets,r=this.targets,s=Math.max(n.length,r.length);this.fireSyntheticInOutEvents(t,e,{oldTarget:i,evtOut:"mouseout",canvasEvtOut:"mouse:out",evtIn:"mouseover",canvasEvtIn:"mouse:over"});for(var o=0;o<s;o++)this.fireSyntheticInOutEvents(r[o],e,{oldTarget:n[o],evtOut:"mouseout",evtIn:"mouseover"});this._hoveredTarget=t,this._hoveredTargets=this.targets.concat()},_fireEnterLeaveEvents:function(t,e){var i=this._draggedoverTarget,n=this._hoveredTargets,r=this.targets,s=Math.max(n.length,r.length);this.fireSyntheticInOutEvents(t,e,{oldTarget:i,evtOut:"dragleave",evtIn:"dragenter"});for(var o=0;o<s;o++)this.fireSyntheticInOutEvents(r[o],e,{oldTarget:n[o],evtOut:"dragleave",evtIn:"dragenter"});this._draggedoverTarget=t},fireSyntheticInOutEvents:function(t,e,i){var n,r,s,o=i.oldTarget,a=o!==t,h=i.canvasEvtIn,l=i.canvasEvtOut;a&&(n={e:e,target:t,previousTarget:o},r={e:e,target:o,nextTarget:t}),s=t&&a,o&&a&&(l&&this.fire(l,r),o.fire(i.evtOut,r)),s&&(h&&this.fire(h,n),t.fire(i.evtIn,n))},__onMouseWheel:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()},_transformObject:function(t){var e=this.getPointer(t),i=this._currentTransform;i.reset=!1,i.shiftKey=t.shiftKey,i.altKey=t[this.centeredKey],this._performTransformAction(t,i,e),i.actionPerformed&&this.requestRenderAll()},_performTransformAction:function(t,e,i){var n=i.x,r=i.y,s=e.action,o=!1,a=e.actionHandler;a&&(o=a(t,e,n,r)),"drag"===s&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o},_fire:b.controlsUtils.fireEvent,_setCursorFromEvent:function(t,e){if(!e)return this.setCursor(this.defaultCursor),!1;var i=e.hoverCursor||this.hoverCursor,n=this._activeObject&&"activeSelection"===this._activeObject.type?this._activeObject:null,r=(!n||!n.contains(e))&&e._findTargetCorner(this.getPointer(t,!0));r?this.setCursor(this.getCornerCursor(r,e,t)):(e.subTargetCheck&&this.targets.concat().reverse().map(function(t){i=t.hoverCursor||i}),this.setCursor(i))},getCornerCursor:function(t,e,i){var n=e.controls[t];return n.cursorStyleHandler(i,n,e)}})}(),v=Math.min,y=Math.max,b.util.object.extend(b.Canvas.prototype,{_shouldGroup:function(t,e){var i=this._activeObject;return i&&this._isSelectionKeyPressed(t)&&e&&e.selectable&&this.selection&&(i!==e||"activeSelection"===i.type)&&!e.onSelect({e:t})},_handleGrouping:function(t,e){var i=this._activeObject;i.__corner||(e!==i||(e=this.findTarget(t,!0))&&e.selectable)&&(i&&"activeSelection"===i.type?this._updateActiveSelection(e,t):this._createActiveSelection(e,t))},_updateActiveSelection:function(t,e){var i=this._activeObject,n=i._objects.slice(0);i.contains(t)?(i.removeWithUpdate(t),this._hoveredTarget=t,this._hoveredTargets=this.targets.concat(),1===i.size()&&this._setActiveObject(i.item(0),e)):(i.addWithUpdate(t),this._hoveredTarget=i,this._hoveredTargets=this.targets.concat()),this._fireSelectionEvents(n,e)},_createActiveSelection:function(t,e){var i=this.getActiveObjects(),n=this._createGroup(t);this._hoveredTarget=n,this._setActiveObject(n,e),this._fireSelectionEvents(i,e)},_createGroup:function(t){var e=this._objects,i=e.indexOf(this._activeObject)<e.indexOf(t)?[this._activeObject,t]:[t,this._activeObject];return this._activeObject.isEditing&&this._activeObject.exitEditing(),new b.ActiveSelection(i,{canvas:this})},_groupSelectedObjects:function(t){var e,i=this._collectObjects(t);1===i.length?this.setActiveObject(i[0],t):i.length>1&&(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,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,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,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,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=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,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,o=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,o,e)}):r.__setupCanvas.call(r,n,t,o,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,o=e.util.degreesToRadians,a=!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:a,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,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return n<o&&(t.width=o),r<o&&(t.height=o),t;var a=n/r,h=e.util.limitDimsByArea(a,i),l=e.util.capValue,c=l(o,h.x,s),u=l(o,h.y,s);return n>c&&(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,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==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=l>y||c>w;v=E||(l<.9*y||c<.9*w)&&y>h&&w>h,E&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.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?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,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"#<fabric."+s(this.type)+">"},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,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),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(o(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,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*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(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),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(o*this.scaleX/r.zoomX,o*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,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.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(a||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,o(-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 o=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 o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=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,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},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,o=b.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+=o*(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,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))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 o in e)if(!((r=e[o]).o.y<t.y&&r.d.y<t.y||r.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)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:0===t?1e-4:t},scale:function(t){return this._set("scaleX",t),this._set("scaleY",t),this.setCoords()},scaleToWidth:function(t,e){var i=this.getBoundingRect(e).width/this.getScaledWidth();return this.scale(t/this.width/i)},scaleToHeight:function(t,e){var i=this.getBoundingRect(e).height/this.getScaledHeight();return this.scale(t/this.height/i)},calcLineCoords:function(){var i=this.getViewportTransform(),r=this.padding,s=e(this.angle),o=t.cos(s)*r,a=t.sin(s)*r,h=o+a,l=o-a,c=this.calcACoords(),u={tl:n(c.tl,i),tr:n(c.tr,i),bl:n(c.bl,i),br:n(c.br,i)};return r&&(u.tl.x-=l,u.tl.y-=h,u.tr.x+=h,u.tr.y-=l,u.bl.x-=h,u.bl.y+=l,u.br.x+=l,u.br.y+=h),u},calcOCoords:function(){var t=this._calcRotateMatrix(),e=this._calcTranslateMatrix(),n=this.getViewportTransform(),r=i(n,e),s=i(r,t),o=(s=i(s,[1/n[0],0,0,1/n[3],0,0]),this._calculateCurrentDimensions()),a={};return this.forEachControl(function(t,e,i){a[e]=t.positionHandler(o,s,i)}),a},calcACoords:function(){var t=this._calcRotateMatrix(),e=this._calcTranslateMatrix(),r=i(e,t),s=this._getTransformedDimensions(),o=s.x/2,a=s.y/2;return{tl:n({x:-o,y:-a},r),tr:n({x:o,y:-a},r),bl:n({x:-o,y:a},r),br:n({x:o,y:a},r)}},setCoords:function(t){return this.aCoords=this.calcACoords(),this.lineCoords=this.group?this.aCoords:this.calcLineCoords(),t||(this.oCoords=this.calcOCoords(),this._setCornerCoords&&this._setCornerCoords()),this},_calcRotateMatrix:function(){return t.calcRotateMatrix(this)},_calcTranslateMatrix:function(){var t=this.getCenterPoint();return[1,0,0,1,t.x,t.y]},transformMatrixKey:function(t){var e="_",i="";return!t&&this.group&&(i=this.group.transformMatrixKey(t)+e),i+this.top+e+this.left+e+this.scaleX+e+this.scaleY+e+this.skewX+e+this.skewY+e+this.angle+e+this.originX+e+this.originY+e+this.width+e+this.height+e+this.strokeWidth+this.flipX+this.flipY},calcTransformMatrix:function(t){var e=this.calcOwnMatrix();if(t||!this.group)return e;var n=this.transformMatrixKey(t),r=this.matrixCache||(this.matrixCache={});return r.key===n?r.value:(this.group&&(e=i(this.group.calcTransformMatrix(!1),e)),r.key=n,r.value=e,e)},calcOwnMatrix:function(){var e=this.transformMatrixKey(!0),i=this.ownMatrixCache||(this.ownMatrixCache={});if(i.key===e)return i.value;var n=this._calcTranslateMatrix(),r={angle:this.angle,translateX:n[4],translateY:n[5],scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY};return i.key=e,i.value=t.composeMatrix(r),i.value},_getNonTransformedDimensions:function(){var t=this.strokeWidth;return{x:this.width+t,y:this.height+t}},_getTransformedDimensions:function(e,i){void 0===e&&(e=this.skewX),void 0===i&&(i=this.skewY);var n,r,s,o=0===e&&0===i;if(this.strokeUniform?(r=this.width,s=this.height):(r=(n=this._getNonTransformedDimensions()).x,s=n.y),o)return this._finalizeDimensions(r*this.scaleX,s*this.scaleY);var a=t.sizeAfterTransform(r,s,{scaleX:this.scaleX,scaleY:this.scaleY,skewX:e,skewY:i});return this._finalizeDimensions(a.x,a.y)},_finalizeDimensions:function(t,e){return this.strokeUniform?{x:t+this.strokeWidth,y:e+this.strokeWidth}:{x:t,y:e}},_calculateCurrentDimensions:function(){var t=this.getViewportTransform(),e=this._getTransformedDimensions();return n(e,t,!0).scalarAdd(2*this.padding)}})}(),b.util.object.extend(b.Object.prototype,{sendToBack:function(){return this.group?b.StaticCanvas.prototype.sendToBack.call(this.group,this):this.canvas&&this.canvas.sendToBack(this),this},bringToFront:function(){return this.group?b.StaticCanvas.prototype.bringToFront.call(this.group,this):this.canvas&&this.canvas.bringToFront(this),this},sendBackwards:function(t){return this.group?b.StaticCanvas.prototype.sendBackwards.call(this.group,this,t):this.canvas&&this.canvas.sendBackwards(this,t),this},bringForward:function(t){return this.group?b.StaticCanvas.prototype.bringForward.call(this.group,this,t):this.canvas&&this.canvas.bringForward(this,t),this},moveTo:function(t){return this.group&&"activeSelection"!==this.group.type?b.StaticCanvas.prototype.moveTo.call(this.group,this,t):this.canvas&&this.canvas.moveTo(this,t),this}}),function(){function t(t,e){if(e){if(e.toLive)return t+": url(#SVGID_"+e.id+"); ";var i=new b.Color(e),n=t+": "+i.toRgb()+"; ",r=i.getAlpha();return 1!==r&&(n+=t+"-opacity: "+r.toString()+"; "),n}return t+": none; "}var e=b.util.toFixed;b.util.object.extend(b.Object.prototype,{getSvgStyles:function(e){var i=this.fillRule?this.fillRule:"nonzero",n=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):"none",s=this.strokeDashOffset?this.strokeDashOffset:"0",o=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=void 0!==this.opacity?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=e?"":this.getSvgFilter(),d=t("fill",this.fill);return[t("stroke",this.stroke),"stroke-width: ",n,"; ","stroke-dasharray: ",r,"; ","stroke-linecap: ",o,"; ","stroke-dashoffset: ",s,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",i,"; ","opacity: ",l,";",u,c].join("")},getSvgSpanStyles:function(e,i){var n="; ",r=e.fontFamily?"font-family: "+(-1===e.fontFamily.indexOf("'")&&-1===e.fontFamily.indexOf('"')?"'"+e.fontFamily+"'":e.fontFamily)+n:"",s=e.strokeWidth?"stroke-width: "+e.strokeWidth+n:"",o=e.fontSize?"font-size: "+e.fontSize+"px"+n:"",a=e.fontStyle?"font-style: "+e.fontStyle+n:"",h=e.fontWeight?"font-weight: "+e.fontWeight+n:"",l=e.fill?t("fill",e.fill):"",c=e.stroke?t("stroke",e.stroke):"",u=this.getSvgTextDecoration(e);return u&&(u="text-decoration: "+u+n),[c,s,r,o,a,h,u,l,e.deltaY?"baseline-shift: "+-e.deltaY+"; ":"",i?"white-space: pre; ":""].join("")},getSvgTextDecoration:function(t){return["overline","underline","line-through"].filter(function(e){return t[e.replace("-","")]}).join(" ")},getSvgFilter:function(){return this.shadow?"filter: url(#SVGID_"+this.shadow.id+");":""},getSvgCommons:function(){return[this.id?'id="'+this.id+'" ':"",this.clipPath?'clip-path="url(#'+this.clipPath.clipPathId+')" ':""].join("")},getSvgTransform:function(t,e){var i=t?this.calcTransformMatrix():this.calcOwnMatrix();return'transform="'+b.util.matrixToSVG(i)+(e||"")+'" '},_setSVGBg:function(t){if(this.backgroundColor){var i=b.Object.NUM_FRACTION_DIGITS;t.push("\t\t<rect ",this._getFillAttributes(this.backgroundColor),' x="',e(-this.width/2,i),'" y="',e(-this.height/2,i),'" width="',e(this.width,i),'" height="',e(this.height,i),'"></rect>\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,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='<clipPath id="'+h.clipPathId+'" >\n'+h.toClipPathSVG(s)+"</clipPath>\n"),c&&g.push("<g ",a,this.getSvgCommons()," >\n"),g.push("<g ",this.getSvgTransform(!1),c?"":a+this.getSvgCommons()," >\n"),i=[o,l,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)),h&&g.push(n),g.push(t.join("")),g.push("</g>\n"),c&&g.push("</g>\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<s;r++)if(!n(t[r],e[r]))return!1;return!0}if(t&&"object"==typeof t){var o,a=Object.keys(t);if(!e||"object"!=typeof e||!i&&a.length!==Object.keys(e).length)return!1;for(r=0,s=a.length;r<s;r++)if("canvas"!==(o=a[r])&&"group"!==o&&!n(t[o],e[o]))return!1;return!0}}b.util.object.extend(b.Object.prototype,{hasStateChanged:function(t){var i="_"+(t=t||e);return Object.keys(this[i]).length<this[t].length||!n(this[i],this,!0)},saveState:function(t){var n=t&&t.propertySet||e,r="_"+n;return this[r]?(i(this,r,this[n]),t&&t.stateProperties&&i(this,r,t.stateProperties),this):this.setupState(t)},setupState:function(t){var i=(t=t||{}).propertySet||e;return t.propertySet=i,this["_"+i]={},this.saveState(t),this}})}(),function(){var t=b.util.degreesToRadians;b.util.object.extend(b.Object.prototype,{_findTargetCorner:function(t,e){if(!this.hasControls||this.group||!this.canvas||this.canvas._activeObject!==this)return!1;var i,n,r,s=t.x,o=t.y,a=Object.keys(this.oCoords),h=a.length-1;for(this.__corner=0;h>=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},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,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!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),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&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,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),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,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),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<s;r++)t=i[r],e=r!==s-1,n.push(this._animate(t,arguments[0][t],arguments[1],e));return n}return this._animate.apply(this,arguments)},_animate:function(t,e,i,n){var r,s=this;e=e.toString(),i=i?b.util.object.clone(i):{},~t.indexOf(".")&&(r=t.split("."));var o=s.colorProperties.indexOf(t)>-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={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,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),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,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h: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["<line ","COMMON_PARTS",'x1="',t.x1,'" y1="',t.y1,'" x2="',t.x2,'" y2="',t.y2,'" />\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),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,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=["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',this.radius,'" />\n'];else{var r=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['<path d="M '+e.util.cos(r)*o+" "+e.util.sin(r)*o," A "+o+" "+o," 0 ",+(n>180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"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["<polygon ","COMMON_PARTS",'points="',[-t+" "+e,"0 "+-e,t+" "+e].join(","),'" />']}}),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["<ellipse ","COMMON_PARTS",'cx="0" cy="0" ','rx="',this.rx,'" ry="',this.ry,'" />\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,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["<rect ","COMMON_PARTS",'x="',-this.width/2,'" y="',-this.height/2,'" rx="',this.rx,'" ry="',this.ry,'" width="',this.width,'" height="',this.height,'" />\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 o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},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,o=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 o(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,o=0,a=this.points.length;o<a;o++)t.push(s(this.points[o].x-i,r),",",s(this.points[o].y-n,r)," ");return["<"+this.type+" ","COMMON_PARTS",'points="',t.join(""),'" />\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<i;s++)e=this.points[s],t.lineTo(e.x-n,e.y-r);return!0},_render:function(t){this.commonRender(t)&&this._renderPaintInOrder(t)},complexity:function(){return this.get("points").length}}),e.Polyline.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polyline.fromElementGenerator=function(t){return function(n,r,s){if(!n)return r(null);s||(s={});var o=e.parsePointsAttribute(n.getAttribute("points")),a=e.parseAttributes(n,e[t].ATTRIBUTE_NAMES);a.fromSVG=!0,r(new e[t](o,i(a,s)))}},e.Polyline.fromElement=e.Polyline.fromElementGenerator("Polyline"),e.Polyline.fromObject=function(t,i){return e.Object._fromObject("Polyline",t,i,"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.projectStrokeOnPoints;e.Polygon?e.warn("fabric.Polygon is already defined"):(e.Polygon=e.util.createClass(e.Polyline,{type:"polygon",_projectStrokeOnPoints:function(){return i(this.points,this)},_render:function(t){this.commonRender(t)&&(t.closePath(),this._renderPaintInOrder(t))}}),e.Polygon.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(),e.Polygon.fromElement=e.Polyline.fromElementGenerator("Polygon"),e.Polygon.fromObject=function(t,i){e.Object._fromObject("Polygon",t,i,"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.array.min,n=e.util.array.max,r=e.util.object.extend,s=e.util.object.clone,o=e.util.toFixed;e.Path?e.warn("fabric.Path is already defined"):(e.Path=e.util.createClass(e.Object,{type:"path",path:null,cacheProperties:e.Object.prototype.cacheProperties.concat("path","fillRule"),stateProperties:e.Object.prototype.stateProperties.concat("path"),initialize:function(t,e){delete(e=s(e||{})).path,this.callSuper("initialize",e),this._setPath(t||[],e)},_setPath:function(t,i){this.path=e.util.makePathSimpler(Array.isArray(t)?t:e.util.parsePath(t)),e.Polyline.prototype._setPositionDimensions.call(this,i||{})},_renderPathCommands:function(t){var e,i=0,n=0,r=0,s=0,o=0,a=0,h=-this.pathOffset.x,l=-this.pathOffset.y;t.beginPath();for(var c=0,u=this.path.length;c<u;++c)switch((e=this.path[c])[0]){case"L":r=e[1],s=e[2],t.lineTo(r+h,s+l);break;case"M":i=r=e[1],n=s=e[2],t.moveTo(r+h,s+l);break;case"C":r=e[5],s=e[6],o=e[3],a=e[4],t.bezierCurveTo(e[1]+h,e[2]+l,o+h,a+l,r+h,s+l);break;case"Q":t.quadraticCurveTo(e[1]+h,e[2]+l,e[3]+h,e[4]+l),r=e[3],s=e[4],o=e[1],a=e[2];break;case"z":case"Z":r=i,s=n,t.closePath()}},_render:function(t){this._renderPathCommands(t),this._renderPaintInOrder(t)},toString:function(){return"#<fabric.Path ("+this.complexity()+'): { "top": '+this.top+', "left": '+this.left+" }>"},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["<path ","COMMON_PARTS",'d="',e.util.joinPath(this.path),'" stroke-linecap="round" ',"/>\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-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=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u<d;++u){switch((t=this.path[u])[0]){case"L":l=t[1],c=t[2],r=[];break;case"M":a=l=t[1],h=c=t[2],r=[];break;case"C":r=e.util.getBoundsOfCurve(l,c,t[1],t[2],t[3],t[4],t[5],t[6]),l=t[5],c=t[6];break;case"Q":r=e.util.getBoundsOfCurve(l,c,t[1],t[2],t[1],t[2],t[3],t[4]),l=t[3],c=t[4];break;case"z":case"Z":l=a,c=h}r.forEach(function(t){s.push(t.x),o.push(t.y)}),s.push(l),o.push(c)}var f=i(s)||0,g=i(o)||0;return{left:f,top:g,width:(n(s)||0)-f,height:(n(o)||0)-g}}}),e.Path.fromObject=function(t,i){if("string"==typeof t.sourcePath){var n=t.sourcePath;e.loadSVGFromURL(n,function(e){var n=e[0];n.setOptions(t),i&&i(n)})}else e.Object._fromObject("Path",t,i,"path")},e.Path.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat(["d"]),e.Path.fromElement=function(t,i,n){var s=e.parseAttributes(t,e.Path.ATTRIBUTE_NAMES);s.fromSVG=!0,i(new e.Path(s.d,r(s,n)))})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.array.min,n=e.util.array.max;e.Group||(e.Group=e.util.createClass(e.Object,e.Collection,{type:"group",strokeWidth:0,subTargetCheck:!1,cacheProperties:[],useSetOnGroup:!1,initialize:function(t,e,i){e=e||{},this._objects=[],i&&this.callSuper("initialize",e),this._objects=t||[];for(var n=this._objects.length;n--;)this._objects[n].group=this;if(i)this._updateObjectsACoords();else{var r=e&&e.centerPoint;void 0!==e.originX&&(this.originX=e.originX),void 0!==e.originY&&(this.originY=e.originY),r||this._calcBounds(),this._updateObjectsCoords(r),delete e.centerPoint,this.callSuper("initialize",e)}this.setCoords()},_updateObjectsACoords:function(){for(var t=this._objects.length;t--;)this._objects[t].setCoords(!0)},_updateObjectsCoords:function(t){t=t||this.getCenterPoint();for(var e=this._objects.length;e--;)this._updateObjectCoords(this._objects[e],t)},_updateObjectCoords:function(t,e){var i=t.left,n=t.top;t.set({left:i-e.x,top:n-e.y}),t.group=this,t.setCoords(!0)},toString:function(){return"#<fabric.Group: ("+this.complexity()+")>"},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++)if(this._objects[i].willDrawShadow())return this.ownCaching=!1,!1;return t},willDrawShadow:function(){if(e.Object.prototype.willDrawShadow.call(this))return!0;for(var t=0,i=this._objects.length;t<i;t++)if(this._objects[t].willDrawShadow())return!0;return!1},isOnACache:function(){return this.ownCaching||this.group&&this.group.isOnACache()},drawObject:function(t){for(var e=0,i=this._objects.length;e<i;e++)this._objects[e].render(t);this._drawClipPath(t,this.clipPath)},isCacheDirty:function(t){if(this.callSuper("isCacheDirty",t))return!0;if(!this.statefullCache)return!1;for(var e=0,i=this._objects.length;e<i;e++)if(this._objects[e].isCacheDirty(!0)){if(this._cacheCanvas){var n=this.cacheWidth/this.zoomX,r=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-n/2,-r/2,n,r)}return!0}return!1},_restoreObjectsState:function(){var t=this.calcOwnMatrix();return this._objects.forEach(function(i){e.util.addTransformToObject(i,t),delete i.group,i.setCoords()}),this},destroy:function(){return this._objects.forEach(function(t){t.set("dirty",!0)}),this._restoreObjectsState()},dispose:function(){this.callSuper("dispose"),this.forEachObject(function(t){t.dispose&&t.dispose()}),this._objects=[]},toActiveSelection:function(){if(this.canvas){var t=this._objects,i=this.canvas;this._objects=[];var n=this.toObject();delete n.objects;var r=new e.ActiveSelection([]);return r.set(n),r.type="activeSelection",i.remove(this),t.forEach(function(t){t.group=r,t.dirty=!0,i.add(t)}),r.canvas=i,r._objects=t,i._activeObject=r,r.setCoords(),r}},ungroupOnCanvas:function(){return this._restoreObjectsState()},setObjectsCoords:function(){return this.forEachObject(function(t){t.setCoords(!0)}),this},_calcBounds:function(t){for(var e,i,n,r,s=[],o=[],a=["tr","br","bl","tl"],h=0,l=this._objects.length,c=a.length;h<l;++h){for(n=(e=this._objects[h]).calcACoords(),r=0;r<c;r++)i=a[r],s.push(n[i].x),o.push(n[i].y);e.aCoords=n}this._getBounds(s,o,t)},_getBounds:function(t,r,s){var o=new e.Point(i(t),i(r)),a=new e.Point(n(t),n(r)),h=o.y||0,l=o.x||0,c=a.x-o.x||0,u=a.y-o.y||0;this.width=c,this.height=u,s||this.setPositionByOrigin({x:l,y:h},"left","top")},_toSVG:function(t){for(var e=["<g ","COMMON_PARTS"," >\n"],i=0,n=this._objects.length;i<n;i++)e.push("\t\t",this._objects[i].toSVG(t));return e.push("</g>\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<n;i++)e.push("\t",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}}),e.Group.fromObject=function(t,i){var n=t.objects,r=e.util.object.clone(t,!0);delete r.objects,"string"!=typeof n?e.util.enlivenObjects(n,function(n){var r=e.util.object.clone(t,!0);delete r.objects,e.util.enlivenObjectEnlivables(t,r,function(){i&&i(new e.Group(n,r,!0))})}):e.loadSVGFromURL(n,function(s){var o=e.util.groupSVGElements(s,t,n);o.set(r),i&&i(o)})})}(e),function(t){var e=t.fabric||(t.fabric={});e.ActiveSelection||(e.ActiveSelection=e.util.createClass(e.Group,{type:"activeSelection",initialize:function(t,i){i=i||{},this._objects=t||[];for(var n=this._objects.length;n--;)this._objects[n].group=this;i.originX&&(this.originX=i.originX),i.originY&&(this.originY=i.originY),this._calcBounds(),this._updateObjectsCoords(),e.Object.prototype.initialize.call(this,i),this.setCoords()},toGroup:function(){var t=this._objects.concat();this._objects=[];var i=e.Object.prototype.toObject.call(this),n=new e.Group([]);if(delete i.type,n.set(i),t.forEach(function(t){t.canvas.remove(t),t.group=n}),n._objects=t,!this.canvas)return n;var r=this.canvas;return r.add(n),r._activeObject=n,n.setCoords(),n},onDeselect:function(){return this.destroy(),!1},toString:function(){return"#<fabric.ActiveSelection: ("+this.complexity()+")>"},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<r;n++)this._objects[n]._renderControls(t,i);t.restore()}}),e.ActiveSelection.fromObject=function(t,i){e.util.enlivenObjects(t.objects,function(n){delete t.objects,i&&i(new e.ActiveSelection(n,t,!0))})})}(e),function(t){var e=b.util.object.extend;t.fabric||(t.fabric={}),t.fabric.Image?b.warn("fabric.Image is already defined."):(b.Image=b.util.createClass(b.Object,{type:"image",strokeWidth:0,srcFromAttribute:!1,_lastScaleX:1,_lastScaleY:1,_filterScalingX:1,_filterScalingY:1,minimumScaleTrigger:.5,stateProperties:b.Object.prototype.stateProperties.concat("cropX","cropY"),cacheProperties:b.Object.prototype.cacheProperties.concat("cropX","cropY"),cacheKey:"",cropX:0,cropY:0,imageSmoothing:!0,initialize:function(t,e){e||(e={}),this.filters=[],this.cacheKey="texture"+b.Object.__uid++,this.callSuper("initialize",e),this._initElement(t,e)},getElement:function(){return this._element||{}},setElement:function(t,e){return this.removeTexture(this.cacheKey),this.removeTexture(this.cacheKey+"_filtered"),this._element=t,this._originalElement=t,this._initConfig(e),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters(),this},removeTexture:function(t){var e=b.filterBackend;e&&e.evictCachesForKey&&e.evictCachesForKey(t)},dispose:function(){this.callSuper("dispose"),this.removeTexture(this.cacheKey),this.removeTexture(this.cacheKey+"_filtered"),this._cacheContext=void 0,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this))},getCrossOrigin:function(){return this._originalElement&&(this._originalElement.crossOrigin||null)},getOriginalSize:function(){var t=this.getElement();return{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}},_stroke:function(t){if(this.stroke&&0!==this.strokeWidth){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}},toObject:function(t){var i=[];this.filters.forEach(function(t){t&&i.push(t.toObject())});var n=e(this.callSuper("toObject",["cropX","cropY"].concat(t)),{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:i});return this.resizeFilter&&(n.resizeFilter=this.resizeFilter.toObject()),n},hasCrop:function(){return this.cropX||this.cropY||this.width<this._element.width||this.height<this._element.height},_toSVG:function(){var t,e=[],i=[],n=this._element,r=-this.width/2,s=-this.height/2,o="",a="";if(!n)return[];if(this.hasCrop()){var h=b.Object.__uid++;e.push('<clipPath id="imageCrop_'+h+'">\n','\t<rect x="'+r+'" y="'+s+'" width="'+this.width+'" height="'+this.height+'" />\n',"</clipPath>\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t<image ","COMMON_PARTS",'xlink:href="',this.getSvgSrc(!0),'" x="',r-this.cropX,'" y="',s-this.cropY,'" width="',n.width||n.naturalWidth,'" height="',n.height||n.height,a,'"',o,"></image>\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t<rect ",'x="',r,'" y="',s,'" width="',this.width,'" height="',this.height,'" style="',this.getSvgStyles(),'"/>\n'],this.fill=l}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'#<fabric.Image: { src: "'+this.getSrc()+'" }>'},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 o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.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,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);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(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,o=0,a=0,h=0,l=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=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),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"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];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 o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,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 o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),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)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},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 o={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(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),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 o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},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,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s<a;s+=4)e=o[s],i=o[s+1],n=o[s+2],l?(o[s]=e*h[0]+i*h[1]+n*h[2]+255*h[4],o[s+1]=e*h[5]+i*h[6]+n*h[7]+255*h[9],o[s+2]=e*h[10]+i*h[11]+n*h[12]+255*h[14]):(r=o[s+3],o[s]=e*h[0]+i*h[1]+n*h[2]+r*h[3]+255*h[4],o[s+1]=e*h[5]+i*h[6]+n*h[7]+r*h[8]+255*h[9],o[s+2]=e*h[10]+i*h[11]+n*h[12]+r*h[13]+255*h[14],o[s+3]=e*h[15]+i*h[16]+n*h[17]+r*h[18]+255*h[19])},getUniformLocations:function(t,e){return{uColorMatrix:t.getUniformLocation(e,"uColorMatrix"),uConstants:t.getUniformLocation(e,"uConstants")}},sendUniformData:function(t,e){var i=this.matrix,n=[i[0],i[1],i[2],i[3],i[5],i[6],i[7],i[8],i[10],i[11],i[12],i[13],i[15],i[16],i[17],i[18]],r=[i[4],i[9],i[14],i[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,n),t.uniform4fv(e.uConstants,r)}}),e.Image.filters.ColorMatrix.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Brightness=n(i.BaseFilter,{type:"Brightness",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBrightness;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += uBrightness;\ngl_FragColor = color;\n}",brightness:0,mainParameter:"brightness",applyTo2d:function(t){if(0!==this.brightness){var e,i=t.imageData.data,n=i.length,r=Math.round(255*this.brightness);for(e=0;e<n;e+=4)i[e]=i[e]+r,i[e+1]=i[e+1]+r,i[e+2]=i[e+2]+r}},getUniformLocations:function(t,e){return{uBrightness:t.getUniformLocation(e,"uBrightness")}},sendUniformData:function(t,e){t.uniform1f(e.uBrightness,this.brightness)}}),e.Image.filters.Brightness.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,r=e.util.createClass;n.Convolute=r(n.BaseFilter,{type:"Convolute",opaque:!1,matrix:[0,0,0,0,1,0,0,0,0],fragmentSource:{Convolute_3_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_3_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_5_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_5_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_7_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_7_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",Convolute_9_1:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n}\n}\ngl_FragColor = color;\n}",Convolute_9_0:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}"},retrieveShader:function(t){var e=Math.sqrt(this.matrix.length),i=this.type+"_"+e+"_"+(this.opaque?1:0),n=this.fragmentSource[i];return t.programCache.hasOwnProperty(i)||(t.programCache[i]=this.createProgram(t.context,n)),t.programCache[i]},applyTo2d:function(t){var e,i,n,r,s,o,a,h,l,c,u,d,f,g=t.imageData,m=g.data,p=this.matrix,_=Math.round(Math.sqrt(p.length)),v=Math.floor(_/2),y=g.width,w=g.height,E=t.ctx.createImageData(y,w),C=E.data,S=this.opaque?1:0;for(u=0;u<w;u++)for(c=0;c<y;c++){for(s=4*(u*y+c),e=0,i=0,n=0,r=0,f=0;f<_;f++)for(d=0;d<_;d++)o=c+d-v,(a=u+f-v)<0||a>=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));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;e<r;e+=4)"average"===s?i=(n[e]+n[e+1]+n[e+2])/3:"lightness"===s?i=(Math.min(n[e],n[e+1],n[e+2])+Math.max(n[e],n[e+1],n[e+2]))/2:"luminosity"===s&&(i=.21*n[e]+.72*n[e+1]+.07*n[e+2]),n[e]=i,n[e+1]=i,n[e+2]=i},retrieveShader:function(t){var e=this.type+"_"+this.mode;if(!t.programCache.hasOwnProperty(e)){var i=this.fragmentSource[this.mode];t.programCache[e]=this.createProgram(t.context,i)}return t.programCache[e]},getUniformLocations:function(t,e){return{uMode:t.getUniformLocation(e,"uMode")}},sendUniformData:function(t,e){t.uniform1i(e.uMode,1)},isNeutralState:function(){return!1}}),e.Image.filters.Grayscale.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Invert=n(i.BaseFilter,{type:"Invert",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uInvert;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nif (uInvert == 1) {\ngl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n} else {\ngl_FragColor = color;\n}\n}",invert:!0,mainParameter:"invert",applyTo2d:function(t){var e,i=t.imageData.data,n=i.length;for(e=0;e<n;e+=4)i[e]=255-i[e],i[e+1]=255-i[e+1],i[e+2]=255-i[e+2]},isNeutralState:function(){return!this.invert},getUniformLocations:function(t,e){return{uInvert:t.getUniformLocation(e,"uInvert")}},sendUniformData:function(t,e){t.uniform1i(e.uInvert,this.invert)}}),e.Image.filters.Invert.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,r=e.util.createClass;n.Noise=r(n.BaseFilter,{type:"Noise",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uStepH;\nuniform float uNoise;\nuniform float uSeed;\nvarying vec2 vTexCoord;\nfloat rand(vec2 co, float seed, float vScale) {\nreturn fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n}\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\ngl_FragColor = color;\n}",mainParameter:"noise",noise:0,applyTo2d:function(t){if(0!==this.noise){var e,i,n=t.imageData.data,r=n.length,s=this.noise;for(e=0,r=n.length;e<r;e+=4)i=(.5-Math.random())*s,n[e]+=i,n[e+1]+=i,n[e+2]+=i}},getUniformLocations:function(t,e){return{uNoise:t.getUniformLocation(e,"uNoise"),uSeed:t.getUniformLocation(e,"uSeed")}},sendUniformData:function(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())},toObject:function(){return i(this.callSuper("toObject"),{noise:this.noise})}}),e.Image.filters.Noise.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Pixelate=n(i.BaseFilter,{type:"Pixelate",blocksize:4,mainParameter:"blocksize",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uBlocksize;\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nfloat blockW = uBlocksize * uStepW;\nfloat blockH = uBlocksize * uStepW;\nint posX = int(vTexCoord.x / blockW);\nint posY = int(vTexCoord.y / blockH);\nfloat fposX = float(posX);\nfloat fposY = float(posY);\nvec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\nvec4 color = texture2D(uTexture, squareCoords);\ngl_FragColor = color;\n}",applyTo2d:function(t){var e,i,n,r,s,o,a,h,l,c,u,d=t.imageData,f=d.data,g=d.height,m=d.width;for(i=0;i<g;i+=this.blocksize)for(n=0;n<m;n+=this.blocksize)for(r=f[e=4*i*m+4*n],s=f[e+1],o=f[e+2],a=f[e+3],c=Math.min(i+this.blocksize,g),u=Math.min(n+this.blocksize,m),h=i;h<c;h++)for(l=n;l<u;l++)f[e=4*h*m+4*l]=r,f[e+1]=s,f[e+2]=o,f[e+3]=a},isNeutralState:function(){return 1===this.blocksize},getUniformLocations:function(t,e){return{uBlocksize:t.getUniformLocation(e,"uBlocksize"),uStepW:t.getUniformLocation(e,"uStepW"),uStepH:t.getUniformLocation(e,"uStepH")}},sendUniformData:function(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}),e.Image.filters.Pixelate.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.Image.filters,r=e.util.createClass;n.RemoveColor=r(n.BaseFilter,{type:"RemoveColor",color:"#FFFFFF",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\ngl_FragColor.a = 0.0;\n}\n}",distance:.02,useAlpha:!1,applyTo2d:function(t){var i,n,r,s,o=t.imageData.data,a=255*this.distance,h=new e.Color(this.color).getSource(),l=[h[0]-a,h[1]-a,h[2]-a],c=[h[0]+a,h[1]+a,h[2]+a];for(i=0;i<o.length;i+=4)n=o[i],r=o[i+1],s=o[i+2],n>l[0]&&r>l[1]&&s>l[2]&&n<c[0]&&r<c[1]&&s<c[2]&&(o[i+3]=0)},getUniformLocations:function(t,e){return{uLow:t.getUniformLocation(e,"uLow"),uHigh:t.getUniformLocation(e,"uHigh")}},sendUniformData:function(t,i){var n=new e.Color(this.color).getSource(),r=parseFloat(this.distance),s=[0+n[0]/255-r,0+n[1]/255-r,0+n[2]/255-r,1],o=[n[0]/255+r,n[1]/255+r,n[2]/255+r,1];t.uniform4fv(i.uLow,s),t.uniform4fv(i.uHigh,o)},toObject:function(){return i(this.callSuper("toObject"),{color:this.color,distance:this.distance})}}),e.Image.filters.RemoveColor.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass,r={Brownie:[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0],Vintage:[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0],Kodachrome:[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0],Technicolor:[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0],Polaroid:[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],Sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],BlackWhite:[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]};for(var s in r)i[s]=n(i.ColorMatrix,{type:s,matrix:r[s],mainParameter:!1,colorsOnly:!0}),e.Image.filters[s].fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric,i=e.Image.filters,n=e.util.createClass;i.BlendColor=n(i.BaseFilter,{type:"BlendColor",color:"#F95C63",mode:"multiply",alpha:1,fragmentSource:{multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",diff:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"if (uColor.r < 0.5) {\ngl_FragColor.r *= 2.0 * uColor.r;\n} else {\ngl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n}\nif (uColor.g < 0.5) {\ngl_FragColor.g *= 2.0 * uColor.g;\n} else {\ngl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n}\nif (uColor.b < 0.5) {\ngl_FragColor.b *= 2.0 * uColor.b;\n} else {\ngl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n}\n",tint:"gl_FragColor.rgb *= (1.0 - uColor.a);\ngl_FragColor.rgb += uColor.rgb;\n"},buildSource:function(t){return"precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ngl_FragColor = color;\nif (color.a > 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,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d<c;d+=4)switch(s=l[d],o=l[d+1],a=l[d+2],this.mode){case"multiply":l[d]=s*i/255,l[d+1]=o*n/255,l[d+2]=a*r/255;break;case"screen":l[d]=255-(255-s)*(255-i)/255,l[d+1]=255-(255-o)*(255-n)/255,l[d+2]=255-(255-a)*(255-r)/255;break;case"add":l[d]=s+i,l[d+1]=o+n,l[d+2]=a+r;break;case"diff":case"difference":l[d]=Math.abs(s-i),l[d+1]=Math.abs(o-n),l[d+2]=Math.abs(a-r);break;case"subtract":l[d]=s-i,l[d+1]=o-n,l[d+2]=a-r;break;case"darken":l[d]=Math.min(s,i),l[d+1]=Math.min(o,n),l[d+2]=Math.min(a,r);break;case"lighten":l[d]=Math.max(s,i),l[d+1]=Math.max(o,n),l[d+2]=Math.max(a,r);break;case"overlay":l[d]=i<128?2*s*i/255:255-2*(255-s)*(255-i)/255,l[d+1]=n<128?2*o*n/255:255-2*(255-o)*(255-n)/255,l[d+2]=r<128?2*a*r/255:255-2*(255-a)*(255-r)/255;break;case"exclusion":l[d]=i+s-2*i*s/255,l[d+1]=n+o-2*n*o/255,l[d+2]=r+a-2*r*a/255;break;case"tint":l[d]=i+s*u,l[d+1]=n+o*u,l[d+2]=r+a*u}},getUniformLocations:function(t,e){return{uColor:t.getUniformLocation(e,"uColor")}},sendUniformData:function(t,i){var n=new e.Color(this.color).getSource();n[0]=this.alpha*n[0]/255,n[1]=this.alpha*n[1]/255,n[2]=this.alpha*n[2]/255,n[3]=this.alpha,t.uniform4fv(i.uColor,n)},toObject:function(){return{type:this.type,color:this.color,mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendColor.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric,i=e.Image.filters,n=e.util.createClass;i.BlendImage=n(i.BaseFilter,{type:"BlendImage",image:null,mode:"multiply",alpha:1,vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nuniform mat3 uTransformMatrix;\nvoid main() {\nvTexCoord = aPosition;\nvTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:{multiply:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.rgba *= color2.rgba;\ngl_FragColor = color;\n}",mask:"precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.a = color2.a;\ngl_FragColor = color;\n}"},retrieveShader:function(t){var e=this.type+"_"+this.mode,i=this.fragmentSource[this.mode];return t.programCache.hasOwnProperty(e)||(t.programCache[e]=this.createProgram(t.context,i)),t.programCache[e]},applyToWebGL:function(t){var e=t.context,i=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,i,e.TEXTURE1),this.callSuper("applyToWebGL",t),this.unbindAdditionalTexture(e,e.TEXTURE1)},createTexture:function(t,e){return t.getCachedTexture(e.cacheKey,e._element)},calculateMatrix:function(){var t=this.image,e=t._element.width,i=t._element.height;return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/i,1]},applyTo2d:function(t){var i,n,r,s,o,a,h,l,c,u,d,f=t.imageData,g=t.filterBackend.resources,m=f.data,p=m.length,_=f.width,v=f.height,y=this.image;g.blendImage||(g.blendImage=e.util.createCanvasElement()),u=(c=g.blendImage).getContext("2d"),c.width!==_||c.height!==v?(c.width=_,c.height=v):u.clearRect(0,0,_,v),u.setTransform(y.scaleX,0,0,y.scaleY,y.left,y.top),u.drawImage(y._element,0,0,_,v),d=u.getImageData(0,0,_,v).data;for(var w=0;w<p;w+=4)switch(o=m[w],a=m[w+1],h=m[w+2],l=m[w+3],i=d[w],n=d[w+1],r=d[w+2],s=d[w+3],this.mode){case"multiply":m[w]=o*i/255,m[w+1]=a*n/255,m[w+2]=h*r/255,m[w+3]=l*s/255;break;case"mask":m[w+3]=s}},getUniformLocations:function(t,e){return{uTransformMatrix:t.getUniformLocation(e,"uTransformMatrix"),uImage:t.getUniformLocation(e,"uImage")}},sendUniformData:function(t,e){var i=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,i)},toObject:function(){return{type:this.type,image:this.image&&this.image.toObject(),mode:this.mode,alpha:this.alpha}}}),e.Image.filters.BlendImage.fromObject=function(t,i){e.Image.fromObject(t.image,function(n){var r=e.util.object.clone(t);r.image=n,i(new e.Image.filters.BlendImage(r))})}}(e),function(t){var e=t.fabric||(t.fabric={}),i=Math.pow,n=Math.floor,r=Math.sqrt,s=Math.abs,o=Math.round,a=Math.sin,h=Math.ceil,l=e.Image.filters,c=e.util.createClass;l.Resize=c(l.BaseFilter,{type:"Resize",resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3,getUniformLocations:function(t,e){return{uDelta:t.getUniformLocation(e,"uDelta"),uTaps:t.getUniformLocation(e,"uTaps")}},sendUniformData:function(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)},retrieveShader:function(t){var e=this.getFilterWindow(),i=this.type+"_"+e;if(!t.programCache.hasOwnProperty(i)){var n=this.generateShader(e);t.programCache[i]=this.createProgram(t.context,n)}return t.programCache[i]},getFilterWindow:function(){var t=this.tempScale;return Math.ceil(this.lanczosLobes/t)},getTaps:function(){for(var t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,i=this.getFilterWindow(),n=new Array(i),r=1;r<=i;r++)n[r-1]=t(r*e);return n},generateShader:function(t){for(var e=new Array(t),i=this.fragmentSourceTOP,n=1;n<=t;n++)e[n-1]=n+".0 * uDelta";return i+="uniform float uTaps["+t+"];\n",i+="void main() {\n",i+=" vec4 color = texture2D(uTexture, vTexCoord);\n",i+=" float sum = 1.0;\n",e.forEach(function(t,e){i+=" color += texture2D(uTexture, vTexCoord + "+t+") * uTaps["+e+"];\n",i+=" color += texture2D(uTexture, vTexCoord - "+t+") * uTaps["+e+"];\n",i+=" sum += 2.0 * uTaps["+e+"];\n"}),i+=" gl_FragColor = color / sum;\n",i+="}"},fragmentSourceTOP:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\n",applyTo:function(t){t.webgl?(t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t),t.sourceHeight=t.destinationHeight):this.applyTo2d(t)},isNeutralState:function(){return 1===this.scaleX&&1===this.scaleY},lanczosCreate:function(t){return function(e){if(e>=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(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,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=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")),((a=m.sliceByTwo).width<1.5*i||a.height<r)&&(a.width=1.5*i,a.height=r),(h=a.getContext("2d")).clearRect(0,0,1.5*i,r),h.putImageData(l,0,0),s=n(s),o=n(o);!u||!d;)i=f,r=g,s<n(f*c)?f=n(f*c):(f=s,u=!0),o<n(g*c)?g=n(g*c):(g=o,d=!0),h.drawImage(a,p,_,i,r,v,y,f,g),p=v,_=y,y+=g;return h.getImageData(p,_,s,o)},lanczosResize:function(t,e,o,a,l){var c=t.imageData.data,u=t.ctx.createImageData(a,l),d=u.data,f=this.lanczosCreate(this.lanczosLobes),g=this.rcpScaleX,m=this.rcpScaleY,p=2/this.rcpScaleX,_=2/this.rcpScaleY,v=h(g*this.lanczosLobes/2),y=h(m*this.lanczosLobes/2),w={},E={},C={};return function t(h){var S,b,T,I,x,O,R,A,D,L,M;for(E.x=(h+.5)*g,C.x=n(E.x),S=0;S<l;S++){for(E.y=(S+.5)*m,C.y=n(E.y),x=0,O=0,R=0,A=0,D=0,b=C.x-v;b<=C.x+v;b++)if(!(b<0||b>=e)){L=n(1e3*s(b-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-E.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)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h<a?t(h):u}(0)},bilinearFiltering:function(t,e,i,r,s){var o,a,h,l,c,u,d,f,g,m=0,p=this.rcpScaleX,_=this.rcpScaleY,v=4*(e-1),y=t.imageData.data,w=t.ctx.createImageData(r,s),E=w.data;for(h=0;h<s;h++)for(l=0;l<r;l++)for(c=p*l-(o=n(p*l)),u=_*h-(a=n(_*h)),g=4*(a*e+o),d=0;d<4;d++)f=y[g+d]*(1-c)*(1-u)+y[g+4+d]*c*(1-u)+y[g+v+d]*u*(1-c)+y[g+v+4+d]*c*u,E[m++]=f;return w},hermiteFastResize:function(t,e,i,o,a){for(var l=this.rcpScaleX,c=this.rcpScaleY,u=h(l/2),d=h(c/2),f=t.imageData.data,g=t.ctx.createImageData(o,a),m=g.data,p=0;p<a;p++)for(var _=0;_<o;_++){for(var v=4*(_+p*o),y=0,w=0,E=0,C=0,S=0,b=0,T=0,I=(p+.5)*c,x=n(p*c);x<(p+1)*c;x++)for(var O=s(I-(x+.5))/d,R=(_+.5)*l,A=O*O,D=n(_*l);D<(_+1)*l;D++){var L=s(R-(D+.5))/u,M=r(A+L*L);M>1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/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;e<n;e+=4)i[e]=s*(i[e]-128)+128,i[e+1]=s*(i[e+1]-128)+128,i[e+2]=s*(i[e+2]-128)+128}},getUniformLocations:function(t,e){return{uContrast:t.getUniformLocation(e,"uContrast")}},sendUniformData:function(t,e){t.uniform1f(e.uContrast,this.contrast)}}),e.Image.filters.Contrast.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Saturation=n(i.BaseFilter,{type:"Saturation",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uSaturation;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat rgMax = max(color.r, color.g);\nfloat rgbMax = max(rgMax, color.b);\ncolor.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\ncolor.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\ncolor.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\ngl_FragColor = color;\n}",saturation:0,mainParameter:"saturation",applyTo2d:function(t){if(0!==this.saturation){var e,i,n=t.imageData.data,r=n.length,s=-this.saturation;for(e=0;e<r;e+=4)i=Math.max(n[e],n[e+1],n[e+2]),n[e]+=i!==n[e]?(i-n[e])*s:0,n[e+1]+=i!==n[e+1]?(i-n[e+1])*s:0,n[e+2]+=i!==n[e+2]?(i-n[e+2])*s:0}},getUniformLocations:function(t,e){return{uSaturation:t.getUniformLocation(e,"uSaturation")}},sendUniformData:function(t,e){t.uniform1f(e.uSaturation,-this.saturation)}}),e.Image.filters.Saturation.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Vibrance=n(i.BaseFilter,{type:"Vibrance",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uVibrance;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat max = max(color.r, max(color.g, color.b));\nfloat avg = (color.r + color.g + color.b) / 3.0;\nfloat amt = (abs(max - avg) * 2.0) * uVibrance;\ncolor.r += max != color.r ? (max - color.r) * amt : 0.00;\ncolor.g += max != color.g ? (max - color.g) * amt : 0.00;\ncolor.b += max != color.b ? (max - color.b) * amt : 0.00;\ngl_FragColor = color;\n}",vibrance:0,mainParameter:"vibrance",applyTo2d:function(t){if(0!==this.vibrance){var e,i,n,r,s=t.imageData.data,o=s.length,a=-this.vibrance;for(e=0;e<o;e+=4)i=Math.max(s[e],s[e+1],s[e+2]),n=(s[e]+s[e+1]+s[e+2])/3,r=2*Math.abs(i-n)/255*a,s[e]+=i!==s[e]?(i-s[e])*r:0,s[e+1]+=i!==s[e+1]?(i-s[e+1])*r:0,s[e+2]+=i!==s[e+2]?(i-s[e+2])*r:0}},getUniformLocations:function(t,e){return{uVibrance:t.getUniformLocation(e,"uVibrance")}},sendUniformData:function(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}}),e.Image.filters.Vibrance.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Blur=n(i.BaseFilter,{type:"Blur",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\nconst float nSamples = 15.0;\nvec3 v3offset = vec3(12.9898, 78.233, 151.7182);\nfloat random(vec3 scale) {\nreturn fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n}\nvoid main() {\nvec4 color = vec4(0.0);\nfloat total = 0.0;\nfloat offset = random(v3offset);\nfor (float t = -nSamples; t <= nSamples; t++) {\nfloat percent = (t + offset - 0.5) / nSamples;\nfloat weight = 1.0 - abs(percent);\ncolor += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\ntotal += weight;\n}\ngl_FragColor = color / total;\n}",blur:0,mainParameter:"blur",applyTo:function(t){t.webgl?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},applyTo2d:function(t){t.imageData=this.simpleBlur(t)},simpleBlur:function(t){var i,n,r=t.filterBackend.resources,s=t.imageData.width,o=t.imageData.height;r.blurLayer1||(r.blurLayer1=e.util.createCanvasElement(),r.blurLayer2=e.util.createCanvasElement()),i=r.blurLayer1,n=r.blurLayer2,i.width===s&&i.height===o||(n.width=i.width=s,n.height=i.height=o);var a,h,l,c,u=i.getContext("2d"),d=n.getContext("2d"),f=.06*this.blur*.5;for(u.putImageData(t.imageData,0,0),d.clearRect(0,0,s,o),c=-15;c<=15;c++)l=f*(h=c/15)*s+(a=(Math.random()-.5)/4),d.globalAlpha=1-Math.abs(h),d.drawImage(i,l,a),u.drawImage(n,0,0),d.globalAlpha=1,d.clearRect(0,0,n.width,n.height);for(c=-15;c<=15;c++)l=f*(h=c/15)*o+(a=(Math.random()-.5)/4),d.globalAlpha=1-Math.abs(h),d.drawImage(i,a,l),u.drawImage(n,0,0),d.globalAlpha=1,d.clearRect(0,0,n.width,n.height);t.ctx.drawImage(i,0,0);var g=t.ctx.getImageData(0,0,i.width,i.height);return u.globalAlpha=1,u.clearRect(0,0,i.width,i.height),g},getUniformLocations:function(t,e){return{delta:t.getUniformLocation(e,"uDelta")}},sendUniformData:function(t,e){var i=this.chooseRightDelta();t.uniform2fv(e.delta,i)},chooseRightDelta:function(){var t,e=1,i=[0,0];return this.horizontal?this.aspectRatio>1&&(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],o=1/n[1],a=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<r;e++)this.rVals[e]=255*Math.pow(e/255,s),this.gVals[e]=255*Math.pow(e/255,o),this.bVals[e]=255*Math.pow(e/255,a);for(e=0,r=i.length;e<r;e+=4)i[e]=this.rVals[i[e]],i[e+1]=this.gVals[i[e+1]],i[e+2]=this.bVals[i[e+2]]},getUniformLocations:function(t,e){return{uGamma:t.getUniformLocation(e,"uGamma")}},sendUniformData:function(t,e){t.uniform3fv(e.uGamma,this.gamma)}}),e.Image.filters.Gamma.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Composed=n(i.BaseFilter,{type:"Composed",subFilters:[],initialize:function(t){this.callSuper("initialize",t),this.subFilters=this.subFilters.slice(0)},applyTo:function(t){t.passes+=this.subFilters.length-1,this.subFilters.forEach(function(e){e.applyTo(t)})},toObject:function(){return e.util.object.extend(this.callSuper("toObject"),{subFilters:this.subFilters.map(function(t){return t.toObject()})})},isNeutralState:function(){return!this.subFilters.some(function(t){return!t.isNeutralState()})}}),e.Image.filters.Composed.fromObject=function(t,i){var n=(t.subFilters||[]).map(function(t){return new e.Image.filters[t.type](t)}),r=new e.Image.filters.Composed({subFilters:n});return i&&i(r),r}}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.HueRotation=n(i.ColorMatrix,{type:"HueRotation",rotation:0,mainParameter:"rotation",calculateMatrix:function(){var t=this.rotation*Math.PI,i=e.util.cos(t),n=e.util.sin(t),r=1/3,s=Math.sqrt(r)*n,o=1-i;this.matrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],this.matrix[0]=i+o/3,this.matrix[1]=r*o-s,this.matrix[2]=r*o+s,this.matrix[5]=r*o+s,this.matrix[6]=i+r*o,this.matrix[7]=r*o-s,this.matrix[10]=r*o-s,this.matrix[11]=r*o+s,this.matrix[12]=i+r*o},isNeutralState:function(t){return this.calculateMatrix(),i.BaseFilter.prototype.isNeutralState.call(this,t)},applyTo:function(t){this.calculateMatrix(),i.BaseFilter.prototype.applyTo.call(this,t)}}),e.Image.filters.HueRotation.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.clone;if(e.Text)e.warn("fabric.Text is already defined");else{var n="fontFamily fontWeight fontSize text underline overline linethrough textAlign fontStyle lineHeight textBackgroundColor charSpacing styles direction path pathStartOffset pathSide pathAlign".split(" ");e.Text=e.util.createClass(e.Object,{_dimensionAffectingProps:["fontSize","fontWeight","fontFamily","fontStyle","lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],_reNewline:/\r?\n/,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,type:"text",fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:"left",fontStyle:"normal",lineHeight:1.16,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},textBackgroundColor:"",stateProperties:e.Object.prototype.stateProperties.concat(n),cacheProperties:e.Object.prototype.cacheProperties.concat(n),stroke:null,shadow:null,path:null,pathStartOffset:0,pathSide:"left",pathAlign:"baseline",_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.315,overline:-.88},_fontSizeMult:1.13,charSpacing:0,styles:null,_measuringContext:null,deltaY:0,direction:"ltr",_styleProperties:["stroke","strokeWidth","fill","fontFamily","fontSize","fontWeight","fontStyle","underline","overline","linethrough","deltaY","textBackgroundColor"],__charBounds:[],CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,initialize:function(t,e){this.styles=e&&e.styles||{},this.text=t,this.__skipDimension=!0,this.callSuper("initialize",e),this.path&&this.setPathInfo(),this.__skipDimension=!1,this.initDimensions(),this.setCoords(),this.setupState({propertySet:"_dimensionAffectingProps"})},setPathInfo:function(){var t=this.path;t&&(t.segmentsInfo=e.util.getPathSegmentsInfo(t.path))},getMeasuringContext:function(){return e._measuringContext||(e._measuringContext=this.canvas&&this.canvas.contextCache||e.util.createCanvasElement().getContext("2d")),e._measuringContext},_splitText:function(){var t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t},initDimensions:function(){this.__skipDimension||(this._splitText(),this._clearCache(),this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.saveState({propertySet:"_dimensionAffectingProps"}))},enlargeSpaces:function(){for(var t,e,i,n,r,s,o,a=0,h=this._textLines.length;a<h;a++)if(("justify"===this.textAlign||a!==h-1&&!this.isEndOfWrapping(a))&&(n=0,r=this._textLines[a],(e=this.getLineWidth(a))<this.width&&(o=this.textLines[a].match(this._reSpacesAndTabs)))){i=o.length,t=(this.width-e)/i;for(var l=0,c=r.length;l<=c;l++)s=this.__charBounds[a][l],this._reSpaceAndTab.test(r[l])?(s.width+=t,s.kernedWidth+=t,s.left+=n,n+=t):s.left+=n}},isEndOfWrapping:function(t){return t===this._textLines.length-1},missingNewlineOffset:function(){return 1},toString:function(){return"#<fabric.Text ("+this.complexity()+'): { "text": "'+this.text+'", "fontFamily": "'+this.fontFamily+'" }>'},_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;e<i;e++){var n=this.getLineWidth(e);n>t&&(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,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g<m;g++)if(e=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){n=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,r=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,_=n.length;p<_;p++)s=this.__charBounds[g][p],o=this.getValueOfPropertyAt(g,p,"textBackgroundColor"),f?(t.save(),t.translate(s.renderLeft,s.renderTop),t.rotate(s.angle),t.fillStyle=o,o&&t.fillRect(-s.width/2,-e/this.lineHeight*(1-this._fontSizeFraction),s.width,e/this.lineHeight),t.restore()):o!==r?(a=l+i+u,"rtl"===this.direction&&(a=this.width-a-d),t.fillStyle=r,r&&t.fillRect(a,c,d,e/this.lineHeight),u=s.left,d=s.width,r=o):d+=s.kernedWidth;o&&!f&&(a=l+i+u,"rtl"===this.direction&&(a=this.width-a-d),t.fillStyle=o,t.fillRect(a,c,d,e/this.lineHeight)),c+=e}else c+=e;t.fillStyle=h,this._removeShadow(t)}},getFontCache:function(t){var i=t.fontFamily.toLowerCase();e.charWidthsCache[i]||(e.charWidthsCache[i]={});var n=e.charWidthsCache[i],r=t.fontStyle.toLowerCase()+"_"+(t.fontWeight+"").toLowerCase();return n[r]||(n[r]={}),n[r]},_measureChar:function(t,e,i,n){var r,s,o,a,h=this.getFontCache(e),l=i+t,c=this._getFontDeclaration(e)===this._getFontDeclaration(n),u=e.fontSize/this.CACHE_FONT_SIZE;if(i&&void 0!==h[i]&&(o=h[i]),void 0!==h[t]&&(a=r=h[t]),c&&void 0!==h[l]&&(a=(s=h[l])-o),void 0===r||void 0===o||void 0===s){var d=this.getMeasuringContext();this._setTextStyles(d,e,!0)}return void 0===r&&(a=r=d.measureText(t).width,h[t]=r),void 0===o&&c&&i&&(o=d.measureText(i).width,h[i]=o),c&&void 0===s&&(s=d.measureText(l).width,h[l]=s,a=s-o),{width:r*u,kernedWidth:a*u}},getHeightOfChar:function(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")},measureLine:function(t){var e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e},_measureLine:function(t){var i,n,r,s,o,a,h=0,l=this._textLines[t],c=new Array(l.length),u=0,d=this.path,f="right"===this.pathSide;for(this.__charBounds[t]=c,i=0;i<l.length;i++)n=l[i],s=this._getGraphemeBox(n,t,i,r),c[i]=s,h+=s.kernedWidth,r=n;if(c[i]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize},d){switch(a=d.segmentsInfo[d.segmentsInfo.length-1].length,(o=e.util.getPointOnPath(d.path,0,d.segmentsInfo)).x+=d.pathOffset.x,o.y+=d.pathOffset.y,this.textAlign){case"left":u=f?a-h:0;break;case"center":u=(a-h)/2;break;case"right":u=f?0:a-h}for(u+=this.pathStartOffset*(f?-1:1),i=f?l.length-1:0;f?i>=0:i<l.length;f?i--:i++)s=c[i],u>a?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.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;n<r;n++)i=Math.max(this.getHeightOfChar(t,n),i);return this.__lineHeights[t]=i*this.lineHeight*this._fontSizeMult},calcTextHeight:function(){for(var t,e=0,i=0,n=this._textLines.length;i<n;i++)t=this.getHeightOfLine(i),e+=i===n-1?t/this.lineHeight:t;return e},_getLeftOffset:function(){return"ltr"===this.direction?-this.width/2:this.width/2},_getTopOffset:function(){return-this.height/2},_renderTextCommon:function(t,e){t.save();for(var i=0,n=this._getLeftOffset(),r=this._getTopOffset(),s=0,o=this._textLines.length;s<o;s++){var a=this.getHeightOfLine(s),h=a/this.lineHeight,l=this._getLineLeftOffset(s);this._renderTextLine(e,t,this._textLines[s],n+l,r+i+h,s),i+=a}t.restore()},_renderTextFill:function(t){(this.fill||this.styleHas("fill"))&&this._renderTextCommon(t,"fillText")},_renderTextStroke:function(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())},_renderChars:function(t,e,i,n,r,s){var o,a,h,l,c,u=this.getHeightOfLine(s),d=-1!==this.textAlign.indexOf("justify"),f="",g=0,m=this.path,p=!d&&0===this.charSpacing&&this.isEmptyStyles(s)&&!m,_="ltr"===this.direction,v="ltr"===this.direction?1:-1,y=e.canvas.getAttribute("dir");if(e.save(),y!==this.direction&&(e.canvas.setAttribute("dir",_?"ltr":"rtl"),e.direction=_?"ltr":"rtl",e.textAlign=_?"left":"right"),r-=u*this._fontSizeFraction/this.lineHeight,p)return this._renderChar(t,e,s,0,i.join(""),n,r,u),void e.restore();for(var w=0,E=i.length-1;w<=E;w++)l=w===E||this.charSpacing||m,f+=i[w],h=this.__charBounds[s][w],0===g?(n+=v*(h.kernedWidth-h.width),g+=h.width):g+=h.kernedWidth,d&&!l&&this._reSpaceAndTab.test(i[w])&&(l=!0),l||(o=o||this.getCompleteStyleDeclaration(s,w),a=this.getCompleteStyleDeclaration(s,w+1),l=this._hasStyleChanged(o,a)),l&&(m?(e.save(),e.translate(h.renderLeft,h.renderTop),e.rotate(h.angle),this._renderChar(t,e,s,w,f,-g/2,0,u),e.restore()):(c=n,this._renderChar(t,e,s,w,f,c,r,u)),f="",o=a,n+=v*g,g=0);e.restore()},_applyPatternGradientTransformText:function(t){var i,n=e.util.createCanvasElement(),r=this.width+this.strokeWidth,s=this.height+this.strokeWidth;return n.width=r,n.height=s,(i=n.getContext("2d")).beginPath(),i.moveTo(0,0),i.lineTo(r,0),i.lineTo(r,s),i.lineTo(0,s),i.closePath(),i.translate(r/2,s/2),i.fillStyle=t.toLive(i),this._applyPatternGradientTransform(i,t),i.fill(),i.createPattern(n,"no-repeat")},handleFiller:function(t,e,i){var n,r;return i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?(n=-this.width/2,r=-this.height/2,t.translate(n,r),t[e]=this._applyPatternGradientTransformText(i),{offsetX:n,offsetY:r}):(t[e]=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):(t[e]=i,{offsetX:0,offsetY:0})},_setStrokeStyles:function(t,e){return t.lineWidth=e.strokeWidth,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",e.stroke)},_setFillStyles:function(t,e){return this.handleFiller(t,"fillStyle",e.fill)},_renderChar:function(t,e,i,n,r,s,o){var a,h,l=this._getStyleDeclaration(i,n),c=this.getCompleteStyleDeclaration(i,n),u="fillText"===t&&c.fill,d="strokeText"===t&&c.stroke&&c.strokeWidth;(d||u)&&(e.save(),u&&(a=this._setFillStyles(e,c)),d&&(h=this._setStrokeStyles(e,c)),e.font=this._getFontDeclaration(c),l&&l.textBackgroundColor&&this._removeShadow(e),l&&l.deltaY&&(o+=l.deltaY),u&&e.fillText(r,s-a.offsetX,o-a.offsetY),d&&e.strokeText(r,s-h.offsetX,o-h.offsetY),e.restore())},setSuperscript:function(t,e){return this._setScript(t,e,this.superscript)},setSubscript:function(t,e){return this._setScript(t,e,this.subscript)},_setScript:function(t,e,i){var n=this.get2DCursorLocation(t,!0),r=this.getValueOfPropertyAt(n.lineIndex,n.charIndex,"fontSize"),s=this.getValueOfPropertyAt(n.lineIndex,n.charIndex,"deltaY"),o={fontSize:r*i.size,deltaY:s+r*i.baseline};return this.setSelectionStyles(o,t,e),this},_hasStyleChanged:function(t,e){return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.deltaY!==e.deltaY},_hasStyleChangedForSvg:function(t,e){return this._hasStyleChanged(t,e)||t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough},_getLineLeftOffset:function(t){var e=this.getLineWidth(t),i=this.width-e,n=this.textAlign,r=this.direction,s=0,o=this.isEndOfWrapping(t);return"justify"===n||"justify-center"===n&&!o||"justify-right"===n&&!o||"justify-left"===n&&!o?0:("center"===n&&(s=i/2),"right"===n&&(s=i),"justify-center"===n&&(s=i/2),"justify-right"===n&&(s=i),"rtl"===r&&(s-=i),s)},_clearCache:function(){this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]},_shouldClearDimensionCache:function(){var t=this._forceClearCache;return t||(t=this.hasStateChanged("_dimensionAffectingProps")),t&&(this.dirty=!0,this._forceClearCache=!1),t},getLineWidth:function(t){if(void 0!==this.__lineWidths[t])return this.__lineWidths[t];var e=this.measureLine(t).width;return this.__lineWidths[t]=e,e},_getWidthOfCharSpacing:function(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0},getValueOfPropertyAt:function(t,e,i){var n=this._getStyleDeclaration(t,e);return n&&void 0!==n[i]?n[i]:this[i]},_renderTextDecoration:function(t,e){if(this[e]||this.styleHas(e)){for(var i,n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v=this._getLeftOffset(),y=this._getTopOffset(),w=this.path,E=this._getWidthOfCharSpacing(),C=this.offsets[e],S=0,b=this._textLines.length;S<b;S++)if(i=this.getHeightOfLine(S),this[e]||this.styleHas(e,S)){h=this._textLines[S],m=i/this.lineHeight,s=this._getLineLeftOffset(S),u=0,d=0,l=this.getValueOfPropertyAt(S,0,e),_=this.getValueOfPropertyAt(S,0,"fill"),c=y+m*(1-this._fontSizeFraction),n=this.getHeightOfChar(S,0),o=this.getValueOfPropertyAt(S,0,"deltaY");for(var T=0,I=h.length;T<I;T++)if(f=this.__charBounds[S][T],g=this.getValueOfPropertyAt(S,T,e),p=this.getValueOfPropertyAt(S,T,"fill"),r=this.getHeightOfChar(S,T),a=this.getValueOfPropertyAt(S,T,"deltaY"),w&&g&&p)t.save(),t.fillStyle=_,t.translate(f.renderLeft,f.renderTop),t.rotate(f.angle),t.fillRect(-f.kernedWidth/2,C*r+a,f.kernedWidth,this.fontSize/15),t.restore();else if((g!==l||p!==_||r!==n||a!==o)&&d>0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+C*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}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+o,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,o=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",o].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=[],o=0;o<i.length;o++)n[o]=e.util.string.graphemeSplit(i[o]),s=s.concat(n[o],r);return s.pop(),{_unwrappedLines:n,lines:i,graphemeText:s,graphemeLines:n}},toObject:function(t){var e=n.concat(t),r=this.callSuper("toObject",e);return r.styles=i(this.styles,!0),r.path&&(r.path=this.path.toObject()),r},set:function(t,e){this.callSuper("set",t,e);var i=!1,n=!1;if("object"==typeof t)for(var r in t)"path"===r&&this.setPathInfo(),i=i||-1!==this._dimensionAffectingProps.indexOf(r),n=n||"path"===r;else i=-1!==this._dimensionAffectingProps.indexOf(t),n="path"===t;return n&&this.setPathInfo(),i&&(this.initDimensions(),this.setCoords()),this},complexity:function(){return 1}}),e.Text.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size letter-spacing text-decoration text-anchor".split(" ")),e.Text.DEFAULT_SVG_FONT_SIZE=16,e.Text.fromElement=function(t,n,r){if(!t)return n(null);var s=e.parseAttributes(t,e.Text.ATTRIBUTE_NAMES),o=s.textAnchor||"left";if((r=e.util.object.extend(r?i(r):{},s)).top=r.top||0,r.left=r.left||0,s.textDecoration){var a=s.textDecoration;-1!==a.indexOf("underline")&&(r.underline=!0),-1!==a.indexOf("overline")&&(r.overline=!0),-1!==a.indexOf("line-through")&&(r.linethrough=!0),delete r.textDecoration}"dx"in s&&(r.left+=s.dx),"dy"in s&&(r.top+=s.dy),"fontSize"in r||(r.fontSize=e.Text.DEFAULT_SVG_FONT_SIZE);var h="";"textContent"in t?h=t.textContent:"firstChild"in t&&null!==t.firstChild&&"data"in t.firstChild&&null!==t.firstChild.data&&(h=t.firstChild.data),h=h.replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," ");var l=r.strokeWidth;r.strokeWidth=0;var c=new e.Text(h,r),u=c.getScaledHeight()/c.height,d=((c.height+c.strokeWidth)*c.lineHeight-c.height)*u,f=c.getScaledHeight()+d,g=0;"center"===o&&(g=c.getScaledWidth()/2),"right"===o&&(g=c.getScaledWidth()),c.set({left:c.left-g,top:c.top-(f-c.fontSize*(.07+c._fontSizeFraction))/c.lineHeight,strokeWidth:void 0!==l?l:1}),n(c)},e.Text.fromObject=function(t,n){var r=i(t),s=t.path;return delete r.path,e.Object._fromObject("Text",r,function(t){s?e.Object._fromObject("Path",s,function(e){t.set("path",e),n(t)},"path"):n(t)},"text")},e.Text.genericFonts=["sans-serif","serif","cursive","fantasy","monospace"],e.util.createAccessors&&e.util.createAccessors(e.Text)}}(e),b.util.object.extend(b.Text.prototype,{isEmptyStyles:function(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;var e=void 0===t?this.styles:{line:this.styles[t]};for(var i in e)for(var n in e[i])for(var r in e[i][n])return!1;return!0},styleHas:function(t,e){if(!this.styles||!t||""===t)return!1;if(void 0!==e&&!this.styles[e])return!1;var i=void 0===e?this.styles:{0:this.styles[e]};for(var n in i)for(var r in i[n])if(void 0!==i[n][r][t])return!0;return!1},cleanStyle:function(t){if(!this.styles||!t||""===t)return!1;var e,i,n=this.styles,r=0,s=!0,o=0;for(var a in n){for(var h in e=0,n[a]){var l;r++,(l=n[a][h]).hasOwnProperty(t)?(i?l[t]!==i&&(s=!1):i=l[t],l[t]===this[t]&&delete l[t]):s=!1,0!==Object.keys(l).length?e++:delete n[a][h]}0===e&&delete n[a]}for(var c=0;c<this._textLines.length;c++)o+=this._textLines[c].length;s&&r===o&&(this[t]=i,this.removeStyle(t))},removeStyle:function(t){if(this.styles&&t&&""!==t){var e,i,n,r=this.styles;for(i in r){for(n in e=r[i])delete e[n][t],0===Object.keys(e[n]).length&&delete e[n];0===Object.keys(e).length&&delete r[i]}}},_extendStyles:function(t,e){var i=this.get2DCursorLocation(t);this._getLineStyle(i.lineIndex)||this._setLineStyle(i.lineIndex),this._getStyleDeclaration(i.lineIndex,i.charIndex)||this._setStyleDeclaration(i.lineIndex,i.charIndex,{}),b.util.object.extend(this._getStyleDeclaration(i.lineIndex,i.charIndex),e)},get2DCursorLocation:function(t,e){void 0===t&&(t=this.selectionStart);for(var i=e?this._unwrappedTextLines:this._textLines,n=i.length,r=0;r<n;r++){if(t<=i[r].length)return{lineIndex:r,charIndex:t};t-=i[r].length+this.missingNewlineOffset(r)}return{lineIndex:r-1,charIndex:i[r-1].length<t?i[r-1].length:t}},getSelectionStyles:function(t,e,i){void 0===t&&(t=this.selectionStart||0),void 0===e&&(e=this.selectionEnd||t);for(var n=[],r=t;r<e;r++)n.push(this.getStyleAtPosition(r,i));return n},getStyleAtPosition:function(t,e){var i=this.get2DCursorLocation(t);return(e?this.getCompleteStyleDeclaration(i.lineIndex,i.charIndex):this._getStyleDeclaration(i.lineIndex,i.charIndex))||{}},setSelectionStyles:function(t,e,i){void 0===e&&(e=this.selectionStart||0),void 0===i&&(i=this.selectionEnd||e);for(var n=e;n<i;n++)this._extendStyles(n,t);return this._forceClearCache=!0,this},_getStyleDeclaration:function(t,e){var i=this.styles&&this.styles[t];return i?i[e]:null},getCompleteStyleDeclaration:function(t,e){for(var i,n=this._getStyleDeclaration(t,e)||{},r={},s=0;s<this._styleProperties.length;s++)r[i=this._styleProperties[s]]=void 0===n[i]?this[i]:n[i];return r},_setStyleDeclaration:function(t,e,i){this.styles[t][e]=i},_deleteStyleDeclaration:function(t,e){delete this.styles[t][e]},_getLineStyle:function(t){return!!this.styles[t]},_setLineStyle:function(t){this.styles[t]={}},_deleteLineStyle:function(t){delete this.styles[t]}}),function(){function t(t){t.textDecoration&&(t.textDecoration.indexOf("underline")>-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,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h<i;h++)s+=this.getHeightOfLine(h);e=this._getLineLeftOffset(i);var l=this.__charBounds[i][n];return l&&(o=l.left),0!==this.charSpacing&&n===this._textLines[i].length&&(o-=this._getWidthOfCharSpacing()),r={top:s,left:e+(o>0?o: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"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(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-a/2,h+t.top+l,a,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),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u<h)p=r&&!this.isEndOfWrapping(u)?this.width:this.getLineWidth(u)||5;else if(u===h)if(0===c)p=this.__charBounds[h][c].left;else{var _=this._getWidthOfCharSpacing();p=this.__charBounds[h][c-1].left+this.__charBounds[h][c-1].width-_}d=g,(this.lineHeight<1||u===h&&this.lineHeight>1)&&(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}}}),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<this._text.length;)e++,i++;return t+e},findLineBoundaryLeft:function(t){for(var e=0,i=t-1;!/\n/.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])&&i<this._text.length;)e++,i++;return t+e},searchWordBoundary:function(t,e){for(var i=this._text,n=this._reSpace.test(i[t])?t-1:t,r=i[n],s=b.reNonWord;!s.test(r)&&n>0&&n<i.length;)r=i[n+=e];return s.test(r)&&(n+=1===e?0:1),n},selectWord:function(t){t=t||this.selectionStart;var e=this.searchWordBoundary(t,-1),i=this.searchWordBoundary(t,1);this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()},selectLine:function(t){t=t||this.selectionStart;var e=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);return this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this},enterEditing:function(t){if(!this.isEditing&&this.editable)return this.canvas&&(this.canvas.calcOffset(),this.exitEditingOnOthers(this.canvas)),this.isEditing=!0,this.initHiddenTextarea(t),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick(),this.fire("editing:entered"),this._fireSelectionChanged(),this.canvas?(this.canvas.fire("text:editing:entered",{target:this}),this.initMouseMoveHandler(),this.canvas.requestRenderAll(),this):this},exitEditingOnOthers:function(t){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.selected=!1,t.isEditing&&t.exitEditing()})},initMouseMoveHandler:function(){this.canvas.on("mouse:move",this.mouseMoveHandler)},mouseMoveHandler:function(t){if(this.__isMousedown&&this.isEditing){var e=this.getSelectionStartFromPointer(t.e),i=this.selectionStart,n=this.selectionEnd;(e===this.__selectionStartOnMouseDown&&i!==n||i!==e&&n!==e)&&(e>this.__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,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.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),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i<this._unwrappedTextLines[o].length;i++)delete this.styles[o][i];if(this.styles[h])for(i=l;i<this._unwrappedTextLines[h].length;i++)(n=this.styles[h][i])&&(this.styles[o]||(this.styles[o]={}),this.styles[o][a+i-l]=n);for(i=o+1;i<=h;i++)delete this.styles[i];this.shiftLineStyles(h,o-h)}else if(this.styles[o]){n=this.styles[o];var c,u,d=l-a;for(i=a;i<l;i++)delete n[i];for(u in this.styles[o])(c=parseInt(u,10))>=l&&(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={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(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 o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}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 h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o<t.length;o++)"\n"===t[o]?r[++s]=0:r[s]++;for(r[0]>0&&(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),o=1;o<s;o++)r[o]>0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],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&&i<e?"right"===this._selectionDirection?this.selectionEnd=i:this.selectionStart=i:(e===t?this._selectionDirection="right":"left"===this._selectionDirection&&(this._selectionDirection="right",this.selectionStart=e),this.selectionEnd=i)},setSelectionInBoundaries:function(){var t=this.text.length;this.selectionStart>t?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,o=0,a=0,h=0,l=this._textLines.length;h<l&&s<=i.y;h++)s+=this.getHeightOfLine(h)*this.scaleY,a=h,h>0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;c<u&&(n=r,(r+=this.__charBounds[a][c].kernedWidth*this.scaleX)<=i.x);c++)o++;return this._getNewSelectionStartFromOffset(i,n,r,o,u)},_getNewSelectionStartFromOffset:function(t,e,i,n,r){var s=t.x-e,o=i-t.x,a=n+(o>s||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),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,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,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):l<h&&(i=m?this._text.slice(d+c,d):this._text.slice(u,u-c)),n=a.slice(g.selectionEnd-c,g.selectionEnd),i&&i.length&&(n.length&&(r=this.getSelectionStyles(u,u+1,!1),r=n.map(function(){return r[0]})),f?(s=u,o=d):m?(s=d-i.length,o=d):(s=d,o=d+i.length),this.removeStyleFromTo(s,o)),n.length&&(e&&n.join("")===b.copiedText&&!b.disableStyleCopyPaste&&(r=b.copiedTextStyle),this.insertNewStyleBlock(n,u,r)),this.updateFromTextArea(),this.fire("changed"),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())}},onCompositionStart:function(){this.inCompositionMode=!0},onCompositionEnd:function(){this.inCompositionMode=!1},onCompositionUpdate:function(t){this.compositionStart=t.target.selectionStart,this.compositionEnd=t.target.selectionEnd,this.updateTextareaPosition()},copy:function(){this.selectionStart!==this.selectionEnd&&(b.copiedText=this.getSelectedText(),b.disableStyleCopyPaste?b.copiedTextStyle=null:b.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0)},paste:function(){this.fromPaste=!0},_getClipboardData:function(t){return t&&t.clipboardData||b.window.clipboardData},_getWidthBeforeCursor:function(t,e){var i,n=this._getLineLeftOffset(t);return e>0&&(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,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+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,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;a<h;a++)if((s+=i=this.__charBounds[t][a].width)>e){n=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)<u?a:a-1;break}return n||(o=r.length-1),o},moveCursorDown:function(t){this.selectionStart>=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<text xml:space="preserve" ',this.fontFamily?'font-family="'+this.fontFamily.replace(/"/g,"'")+'" ':"",this.fontSize?'font-size="'+this.fontSize+'" ':"",this.fontStyle?'font-style="'+this.fontStyle+'" ':"",this.fontWeight?'font-weight="'+this.fontWeight+'" ':"",e?'text-decoration="'+e+'" ':"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",t.textSpans.join(""),"</text>\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o<a;o++)i=this._getLineLeftOffset(o),(this.textBackgroundColor||this.styleHas("textBackgroundColor",o))&&this._setSVGTextLineBg(r,o,e+i,s),this._setSVGTextLineText(n,o,e+i,s),s+=this.getHeightOfLine(o);return{textSpans:n,textBgRects:r}},_createTextCharSpan:function(i,n,r,s){var o=i!==i.trim()||i.match(e),a=this.getSvgSpanStyles(n,o),h=a?'style="'+a+'"':"",l=n.deltaY,c="",u=b.Object.NUM_FRACTION_DIGITS;return l&&(c=' dy="'+t(l,u)+'" '),['<tspan x="',t(r,u),'" y="',t(s,u),'" ',c,h,">",b.util.string.escapeXml(i),"</tspan>"].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t<rect ",this._getFillAttributes(i),' x="',t(n,a),'" y="',t(r,a),'" width="',t(s,a),'" height="',t(o,a),'"></rect>\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;u<d;u++)r=this.__charBounds[e][u],(s=this.getValueOfPropertyAt(e,u,"textBackgroundColor"))!==c?(c&&this._pushTextBgRect(t,c,i+l,n,h,a),l=r.left,h=r.width,c=s):h+=r.kernedWidth;s&&this._pushTextBgRect(t,s,i+l,n,h,a)},_getFillAttributes:function(t){var e=t&&"string"==typeof t?new b.Color(t):"";return e&&e.getSource()&&1!==e.getAlpha()?'opacity="'+e.getAlpha()+'" fill="'+e.setAlpha(1).toRgb()+'"':'fill="'+t+'"'},_getSVGLineTopOffset:function(t){for(var e,i=0,n=0;n<t;n++)i+=this.getHeightOfLine(n);return e=this.getHeightOfLine(n),{lineTop:i,offset:(this._fontSizeMult-this._fontSizeFraction)*e/(this.lineHeight*this._fontSizeMult)}},getSvgStyles:function(t){return b.Object.prototype.getSvgStyles.call(this,t)+" white-space: pre;"}})}(),function(t){var e=t.fabric||(t.fabric={});e.Textbox=e.util.createClass(e.IText,e.Observable,{type:"textbox",minWidth:20,dynamicMinWidth:2,__cachedLines:null,lockScalingFlip:!0,noScaleCache:!1,_dimensionAffectingProps:e.Text.prototype._dimensionAffectingProps.concat("width"),_wordJoiners:/[ \t\r]/,splitByGrapheme:!1,initDimensions:function(){this.__skipDimension||(this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.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;s<t.graphemeLines.length;s++)"\n"===t.graphemeText[n]&&s>0?(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],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||h<e))for(var l in i[a][h])return!1;return!0},_getStyleDeclaration:function(t,e){if(this._styleMap&&!this.isWrapping){var i=this._styleMap[t];if(!i)return null;t=i.line,e=i.offset+e}return this.callSuper("_getStyleDeclaration",t,e)},_setStyleDeclaration:function(t,e,i){var n=this._styleMap[t];t=n.line,e=n.offset+e,this.styles[t][e]=i},_deleteStyleDeclaration:function(t,e){var i=this._styleMap[t];t=i.line,e=i.offset+e,delete this.styles[t][e]},_getLineStyle:function(t){var e=this._styleMap[t];return!!this.styles[e.line]},_setLineStyle:function(t){var e=this._styleMap[t];this.styles[e.line]={}},_wrapText:function(t,e){var i,n=[];for(this.isWrapping=!0,i=0;i<t.length;i++)n=n.concat(this._wrapLine(t[i],i,e));return this.isWrapping=!1,n},_measureWord:function(t,e,i){var n,r=0;i=i||0;for(var s=0,o=t.length;s<o;s++)r+=this._getGraphemeBox(t[s],e,s+i,n,!0).kernedWidth,n=t[s];return r},_wrapLine:function(t,i,n,r){var s=0,o=this.splitByGrapheme,a=[],h=[],l=o?e.util.string.graphemeSplit(t):t.split(this._wordJoiners),c="",u=0,d=o?"":" ",f=0,g=0,m=0,p=!0,_=this._getWidthOfCharSpacing();r=r||0,0===l.length&&l.push([]),n-=r;for(var v=0;v<l.length;v++)c=o?l[v]:e.util.string.graphemeSplit(l[v]),f=this._measureWord(c,i,u),u+=c.length,(s+=g+f-_)>n&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},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<n.length;s++)r[s]=n[s].join("");return i.lines=r,i.graphemeLines=n,i},getMinWidth:function(){return Math.max(this.minWidth,this.dynamicMinWidth)},_removeExtraneousStyles:function(){var t={};for(var e in this._styleMap)this._textLines[e]&&(t[this._styleMap[e].line]=1);for(var e in this.styles)t[e]||delete this.styles[e]},toObject:function(t){return this.callSuper("toObject",["minWidth","splitByGrapheme"].concat(t))}}),e.Textbox.fromObject=function(t,i){return e.Object._fromObject("Textbox",t,i,"text")}}(e),function(){var t=b.controlsUtils,e=t.scaleSkewCursorStyleHandler,i=t.scaleCursorStyleHandler,n=t.scalingEqually,r=t.scalingYOrSkewingX,s=t.scalingXOrSkewingY,o=t.scaleOrSkewActionName,a=b.Object.prototype.controls;if(a.ml=new b.Control({x:-.5,y:0,cursorStyleHandler:e,actionHandler:s,getActionName:o}),a.mr=new b.Control({x:.5,y:0,cursorStyleHandler:e,actionHandler:s,getActionName:o}),a.mb=new b.Control({x:0,y:.5,cursorStyleHandler:e,actionHandler:r,getActionName:o}),a.mt=new b.Control({x:0,y:-.5,cursorStyleHandler:e,actionHandler:r,getActionName:o}),a.tl=new b.Control({x:-.5,y:-.5,cursorStyleHandler:i,actionHandler:n}),a.tr=new b.Control({x:.5,y:-.5,cursorStyleHandler:i,actionHandler:n}),a.bl=new b.Control({x:-.5,y:.5,cursorStyleHandler:i,actionHandler:n}),a.br=new b.Control({x:.5,y:.5,cursorStyleHandler:i,actionHandler:n}),a.mtr=new b.Control({x:0,y:-.5,actionHandler:t.rotationWithSnapping,cursorStyleHandler:t.rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:"rotate"}),b.Textbox){var h=b.Textbox.prototype.controls={};h.mtr=a.mtr,h.tr=a.tr,h.br=a.br,h.tl=a.tl,h.bl=a.bl,h.mt=a.mt,h.mb=a.mb,h.mr=new b.Control({x:.5,y:0,actionHandler:t.changeWidth,cursorStyleHandler:e,actionName:"resizing"}),h.ml=new b.Control({x:-.5,y:0,actionHandler:t.changeWidth,cursorStyleHandler:e,actionName:"resizing"})}}()},192:()=>{},898:()=>{},245:()=>{}},ii={};function ni(t){var e=ii[t];if(void 0!==e)return e.exports;var i=ii[t]={exports:{}};return ei[t](i,i.exports,ni),i.exports}ni.d=(t,e)=>{for(var i in e)ni.o(e,i)&&!ni.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ni.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ri={};(()=>{let t;ni.d(ri,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ni(653).fabric:{version:"5.2.1"}})();var si,oi,ai,hi,li=ri.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"}(si||(si={})),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"}(ai||(ai={})),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 ci=t=>"number"==typeof t&&!Number.isNaN(t),ui=t=>"string"==typeof t;var di,fi,gi,mi,pi,_i,vi,yi,wi,Ei,Ci;!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"}(pi||(pi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(_i||(_i={}));let Si=class{get mediaType(){return new Map([["rect",si.DIMT_RECTANGLE],["quad",si.DIMT_QUADRILATERAL],["text",si.DIMT_TEXT],["arc",si.DIMT_ARC],["image",si.DIMT_IMAGE],["polygon",si.DIMT_POLYGON],["line",si.DIMT_LINE],["group",si.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ke(this,fi,"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"===Ke(this,gi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ke(this,gi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ze(this,gi,t,"f")}get coordinateBase(){return Ke(this,gi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(di.add(this),fi.set(this,void 0),gi.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&&!ci(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){Ze(this,fi,t,"f")}getState(){return Ke(this,fi,"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 o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u<d?(v=a/l,g=t+this.get("x")*v,m=e+this.get("y")*v+(h-c*v)/2,p=r+this.get("x")*v,_=s+this.get("y")*v+(h-c*v)/2):(v=h/c,g=t+this.get("x")*v+(a-l*v)/2,m=e+this.get("y")*v,p=r+this.get("x")*v+(a-l*v)/2,_=s+this.get("y")*v);else if("cover"===f)if(u<d){v=h/c;let i=this.get("x")*v-(l*v-a)/2;i=Math.max(i,0),i=Math.min(i,a),g=t+i,m=e+this.get("y")*v,p=r+i,_=s+this.get("y")*v}else{v=a/l;let i=this.get("y")*v-(c*v-h)/2;i=Math.max(i,0),i=Math.min(i,h),g=t+this.get("x")*v,m=e+i,p=r+this.get("x")*v,_=s+i}n.itemClientX=Math.round(g),n.itemClientY=Math.round(m),n.itemPageX=Math.round(p),n.itemPageY=Math.round(_)}for(let t of Object.getOwnPropertyNames(n))Object.defineProperty(i,t,{value:n[t],writable:!0});e&&e.apply(this,[i])},n.set(e,r),this._fabricObject.on("dblclick"===i?"mousedblclick":i,r))}on(t,e){this._on(t,e)}_off(t,e){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&&(n.delete(e),this._fabricObject.off("dblclick"===i?"mousedblclick":i,r))}off(t,e){this._off(t,e)}_setEditable(t){const e=this._fabricObject;t?(e.selectable=!0,e.hasControls=!0,e.hoverCursor=null):(e.selectable=!1,e.hasControls=!1,e.hoverCursor="default")}hasNote(t){return this.mapNoteName_Content.has(t)}addNote(t,e){if(this.hasNote(t.name)&&!e)throw new Error("A note with the same name already exists, please use a different name.");const i=t.content?JSON.parse(JSON.stringify(t.content)):t.content;this.mapNoteName_Content.set(t.name,[i])}getNote(t){const e=this.mapNoteName_Content.get(t);return e?1===e.length?{name:t,content:e[0]?JSON.parse(JSON.stringify(e[0])):e[0]}:{name:t,content:JSON.parse(JSON.stringify(e))}:null}getNotes(){const t=[];for(let e of this.mapNoteName_Content){let i=1===e[1].length?e[1][0]:e[1];i=i?JSON.parse(JSON.stringify(i)):i,t.push({name:e[0],content:i})}return t}updateNote(t,e,i){const n=this.mapNoteName_Content.get(t);if(!n)throw new Error("The note name does not exist.");i||(n.length=0),e=e?JSON.parse(JSON.stringify(e)):e,n.push(e)}deleteNote(t){this.mapNoteName_Content.delete(t)}clearNotes(){this.mapNoteName_Content.clear()}set(t,e){if(!this.extendSet(t,e))if("x"===t){const t=this._fabricObject.group;t?(this._fabricObject.set("left",e-t.left-t.width/2),t.addWithUpdate()):this._fabricObject.set("left",e)}else if("y"===t){const t=this._fabricObject.group;t?(this._fabricObject.set("top",e-t.top-t.height/2),t.addWithUpdate()):this._fabricObject.set("top",e)}else"styleId"===t?this.styleId=e:this._fabricObject.set(t,e);["vertices","startPoint","endPoint","x","y","left","top","width","height","scaleX","scaleY","skewX","skewY","padding","angle","strokeWidth"].includes(t)&&this._fabricObject.setCoords()}get(t){let e=this.extendGet(t);if(void 0===e)if("x"===t){const t=this._fabricObject.group;e=t?this._fabricObject.get("left")+t.left+t.width/2:this._fabricObject.get("left")}else if("y"===t){const t=this._fabricObject.group;e=t?this._fabricObject.get("top")+t.top+t.height/2:this._fabricObject.get("top")}else e="scaledWidth"===t?this._fabricObject.getScaledWidth():"scaledHeight"===t?this._fabricObject.getScaledHeight():["type","mediaType"].includes(t)?this.mediaType:"state"===t?this.getState():"styleId"===t?this.styleId:"drawingLayerId"===t?this.drawingLayerId:this._fabricObject.get(t);return e}remove(){this._drawingLayer&&this._drawingLayer.removeDrawingItems([this])}convertPropFromImageToView(t){if("number"!=typeof t)throw new TypeError("Invalid value.");return t*Ke(this,di,"m",mi).call(this)}convertPropFromViewToImage(t){if("number"!=typeof t)throw new TypeError("Invalid value.");return t/Ke(this,di,"m",mi).call(this)}_setLineWidth(t){if(this._drawingLayer)if("view"===this.coordinateBase)this.set("strokeWidth",this.convertPropFromViewToImage(t));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("strokeWidth",t)}}_getLineWidth(){if(this._drawingLayer){if("view"===this.coordinateBase)return this.convertPropFromImageToView(this.get("strokeWidth"));if("image"===this.coordinateBase)return this.get("strokeWidth");throw new Error("Invalid 'coordinateBase'.")}}_setFontSize(t){if(this._drawingLayer)if("view"===this.coordinateBase)this.set("fontSize",this.convertPropFromViewToImage(t));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("fontSize",t)}}_getFontSize(){if(this._drawingLayer){if("view"===this.coordinateBase)return this.convertPropFromImageToView(this.get("fontSize"));if("image"===this.coordinateBase)return this.get("fontSize");throw new Error("Invalid 'coordinateBase'.")}}};fi=new WeakMap,gi=new WeakMap,di=new WeakSet,mi=function(){const t=this._drawingLayer;if(!t)return 1;const e=t.width,i=t.height,{width:n,height:r}=t.fabricCanvas.wrapperEl.getBoundingClientRect();if(n<=0||r<=0)throw new Error("Unable to get drawing layer dimensions. Layer may not be rendered on the page.");const s=n/e,o=r/i,a=t._getObjectFit();let h=1;return"contain"===a?h=s<o?n/e:r/i:"cover"===a&&(h=s<o?r/i:n/e),h},Si.arrMediaTypes=["rect","arc","polygon","image","text","line","quad"],Si.mapItemType=new Map([[pi.ARC,"arc"],[pi.IMAGE,"image"],[pi.LINE,"line"],[pi.POLYGON,"polygon"],[pi.QUAD,"quad"],[pi.RECT,"rect"],[pi.TEXT,"text"],[pi.GROUP,"group"]]),Si.arrStyleSelectors=["default","selected"],Si.mapItemState=new Map([[_i.DEFAULT,"default"],[_i.SELECTED,"selected"]]);let bi=class extends Si{constructor(t,e){if(super(null,e),vi.set(this,void 0),!P(t))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new li.Rect({left:t.x,top:t.y,width:t.width,height:t.height})),Ze(this,vi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="rect"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth"))),this.set("height",this.convertPropFromViewToImage(this.get("scaledHeight")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth"))),this.set("height",this.convertPropFromImageToView(this.get("scaledHeight")))}setPosition(t){this.setRect(t)}getPosition(){return this.getRect()}updatePosition(){Ke(this,vi,"f")&&this.setRect(Ke(this,vi,"f"))}setRect(t){if(!P(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width)),this.set("height",this.convertPropFromViewToImage(t.height));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width),this.set("height",t.height)}this._drawingLayer.renderAll()}else Ze(this,vi,JSON.parse(JSON.stringify(t)),"f")}getRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ke(this,vi,"f")?JSON.parse(JSON.stringify(Ke(this,vi,"f"))):null}};function Ti(t,e,i){let n=i.points[this.pointIndex].x-i.pathOffset.x,r=i.points[this.pointIndex].y-i.pathOffset.y;return li.util.transformPoint({x:n,y:r},i.calcTransformMatrix())}function Ii(t){let e=new li.Point(t.strokeUniform?1/t.scaleX:1,t.strokeUniform?1/t.scaleY:1).multiply(t.strokeWidth);return new li.Point(t.width+e.x,t.height+e.y)}function xi(t,e,i,n){let r=e.target,s=r.controls[r.__corner],o=r.toLocalPoint(new li.Point(i,n),"center","center"),a=Ii(r),h=r._getTransformedDimensions(0,0),l={x:o.x*a.x/h.x+r.pathOffset.x,y:o.y*a.y/h.y+r.pathOffset.y};return r.points[s.pointIndex]=l,li.controlsUtils.fireEvent("scaling",{e:t,transform:e,pointer:{x:i,y:n}}),!0}function Oi(t,e){return function(i,n,r,s){let o=n.target,a=li.util.transformPoint({x:o.points[t].x-o.pathOffset.x,y:o.points[t].y-o.pathOffset.y},o.calcTransformMatrix()),h=e(i,n,r,s);o._setPositionDimensions({});let l=Ii(o),c=(o.points[t].x-o.pathOffset.x)/l.x,u=(o.points[t].y-o.pathOffset.y)/l.y;return o.setPositionByOrigin(a,c+.5,u+.5),h}}vi=new WeakMap;let Ri=class extends Si{constructor(t,e){if(super(null,e),yi.set(this,void 0),!M(t))throw new TypeError("Invalid 'polygon'.");this._setFabricObject(new li.Polygon(t.points,{objectCaching:!1}));const i=this._fabricObject;let n=i.points.length-1;i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new li.Control({positionHandler:Ti,actionHandler:Oi(i>0?i-1:n,xi),actionName:"modifyPolygon",pointIndex:i}),t},{}),Ze(this,yi,JSON.parse(JSON.stringify(t)),"f"),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 li.Control({positionHandler:Ti,actionHandler:Oi(n>0?n-1:i,xi),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=li.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(){Ke(this,yi,"f")&&this.setPolygon(Ke(this,yi,"f"))}setPolygon(t){if(!M(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 Ze(this,yi,JSON.parse(JSON.stringify(t)),"f")}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 Ke(this,yi,"f")?JSON.parse(JSON.stringify(Ke(this,yi,"f"))):null}};yi=new WeakMap;wi=new WeakMap,Ei=new WeakMap;const Ai=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;n<t.length;n++){let r=t[n][e];void 0!==r&&r.length>i&&(i=r.length)}if(-1===i)break;for(let n=0;n<t.length;n++){if(e>=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<t.length;i++)e=e.concat(...t[i],i===t.length-1?"":"\n");return e})(e)};let Di=class extends Si{constructor(t,e,i){if(super(null,i),Ci.set(this,void 0),!ui(t))throw new TypeError("Invalid 'text'.");if(!P(e))throw new TypeError("Invalid 'rect'.");this._setFabricObject(new li.Textbox(Ai(t),{left:e.x,top:e.y,width:e.width})),this._text=t,Ze(this,Ci,JSON.parse(JSON.stringify(e)),"f"),this._mediaType="text"}extendSet(t,e){if("text"===t)return this._text=e,this._fabricObject.set("text",Ai(e)),!0}extendGet(t){if("text"===t)return this._text}updateCoordinateBaseFromImageToView(){this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),this.set("width",this.convertPropFromViewToImage(this.get("scaledWidth")))}updateCoordinateBaseFromViewToImage(){this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),this.set("width",this.convertPropFromImageToView(this.get("scaledWidth")))}setPosition(t){this.setTextRect(t)}getPosition(){return this.getTextRect()}updatePosition(){Ke(this,Ci,"f")&&this.setTextRect(Ke(this,Ci,"f"))}setText(t){if(!ui(t))throw new TypeError("Invalid 'text'.");this.set("text",t)}getText(){return this.get("text")}setTextRect(t){if(!P(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),this.set("width",this.convertPropFromViewToImage(t.width));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("left",t.x),this.set("top",t.y),this.set("width",t.width)}this._drawingLayer.renderAll()}else Ze(this,Ci,JSON.parse(JSON.stringify(t)),"f")}getTextRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ke(this,Ci,"f")?JSON.parse(JSON.stringify(Ke(this,Ci,"f"))):null}};var Li,Mi;Ci=new WeakMap;Li=new WeakMap;let Fi=class extends Ri{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Mi.set(this,void 0),!F(t))throw new TypeError("Invalid 'quad'.");Ze(this,Mi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Ke(this,Mi,"f")&&this.setQuad(Ke(this,Mi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!F(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 Ze(this,Mi,JSON.parse(JSON.stringify(t)),"f")}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 Ke(this,Mi,"f")?JSON.parse(JSON.stringify(Ke(this,Mi,"f"))):null}};Mi=new WeakMap;class Pi extends Si{constructor(t){super(new li.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 ki=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Ni=t=>!!ui(t)&&""!==t,Bi=t=>!(!ki(t)||"id"in t&&!ci(t.id)||"lineWidth"in t&&!ci(t.lineWidth)||"fillStyle"in t&&!Ni(t.fillStyle)||"strokeStyle"in t&&!Ni(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Ni(t.fontFamily)||"fontSize"in t&&!ci(t.fontSize));class ji{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(P(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!R(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Ui,Vi;class Gi{constructor(){Ui.set(this,new Map),Vi.set(this,!1)}get disposed(){return Ke(this,Vi,"f")}on(t,e){t=t.toLowerCase();const i=Ke(this,Ui,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ke(this,Ui,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ke(this,Ui,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Ke(this,Ui,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Ke(this,Ui,"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 o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ze(this,Vi,!0,"f")}}function Wi(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 Yi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Hi(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))}Ui=new WeakMap,Vi=new WeakMap;const Xi=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};class zi{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 zi.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 zi.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return zi.multiply(t,[e,0,0,0,i,0,0,0,1])}}var qi,Ki,Zi,Ji,$i,Qi,tn,en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,En,Cn,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Er;class Cr{static createDrawingStyle(t){if(!Bi(t))throw new Error("Invalid style definition.");let e,i=Cr.USER_START_STYLE_ID;for(;Ke(Cr,qi,"f",Ki).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Ke(Cr,qi,"f",Zi))n.hasOwnProperty(t)||(n[t]=Ke(Cr,qi,"f",Zi)[t]);return Ke(Cr,qi,"f",Ki).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ke(Cr,qi,"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(Ke(Cr,qi,"f",Ki).values())))}static _updateDrawingStyle(t,e){if(!Bi(e))throw new Error("Invalid style definition.");const i=Ke(Cr,qi,"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)}}qi=Cr,Cr.STYLE_BLUE_STROKE=1,Cr.STYLE_GREEN_STROKE=2,Cr.STYLE_ORANGE_STROKE=3,Cr.STYLE_YELLOW_STROKE=4,Cr.STYLE_BLUE_STROKE_FILL=5,Cr.STYLE_GREEN_STROKE_FILL=6,Cr.STYLE_ORANGE_STROKE_FILL=7,Cr.STYLE_YELLOW_STROKE_FILL=8,Cr.STYLE_BLUE_STROKE_TRANSPARENT=9,Cr.STYLE_GREEN_STROKE_TRANSPARENT=10,Cr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Cr.USER_START_STYLE_ID=1024,Ki={value:new Map([[Cr.STYLE_BLUE_STROKE,{id:Cr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_GREEN_STROKE,{id:Cr.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}],[Cr.STYLE_ORANGE_STROKE,{id:Cr.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}],[Cr.STYLE_YELLOW_STROKE,{id:Cr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_BLUE_STROKE_FILL,{id:Cr.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}],[Cr.STYLE_GREEN_STROKE_FILL,{id:Cr.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}],[Cr.STYLE_ORANGE_STROKE_FILL,{id:Cr.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}],[Cr.STYLE_YELLOW_STROKE_FILL,{id:Cr.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}],[Cr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Cr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Cr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Cr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Zi={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&&(li.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(li.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),li.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},li.Object.prototype.transparentCorners=!1,li.Object.prototype.cornerSize=20,li.Object.prototype.touchCornerSize=100,li.Object.prototype.cornerColor="rgb(254,142,20)",li.Object.prototype.cornerStyle="circle",li.Object.prototype.strokeUniform=!0,li.Object.prototype.hasBorders=!1,li.Canvas.prototype.containerClass="",li.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=li.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=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 h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},li.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;i<t.touches.length;i++){let n=t.touches[i];if(e=this.findTarget(n),e)break}100===this.id&&!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),100===this.id&&e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();let i=this.upperCanvasEl,n=this._getEventPrefix();li.util.addListener(li.document,"touchend",this._onTouchEnd,{passive:!1}),li.util.addListener(li.document,"touchmove",this._onMouseMove,{passive:!1}),li.util.removeListener(i,n+"down",this._onMouseDown)},li.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 o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?li.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;y<c.length;y++)u=a?c[y]:li.util.string.graphemeSplit(c[y]),g=this._measureWord(u,e,d),d+=u.length,(o+=m+g-v)>i&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Sr{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 li.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.fabricCanvas.id=e,this.id=e,e){case Sr.DDN_LAYER_ID:n=Cr.getDrawingStyle(Cr.STYLE_BLUE_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_BLUE_STROKE_FILL);break;case Sr.DBR_LAYER_ID:n=Cr.getDrawingStyle(Cr.STYLE_ORANGE_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_ORANGE_STROKE_FILL);break;case Sr.DLR_LAYER_ID:n=Cr.getDrawingStyle(Cr.STYLE_GREEN_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_GREEN_STROKE_FILL);break;default:n=Cr.getDrawingStyle(Cr.STYLE_YELLOW_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_YELLOW_STROKE_FILL)}for(let t of Si.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 Cr.getDrawingStyle(t.styleId);return Cr.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=Cr.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=Cr.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Cr.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Cr.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 Si))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 Si.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Cr.getDrawingStyle(t.styleId);else{s=Cr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Cr.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 Si.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Cr.getDrawingStyle(t.styleId);else{s=Cr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Cr.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 o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;e<n.length;e++)if(t._zIndex<n[e].getDrawingItem()._zIndex){a=e;break}this._arrDrwaingItem.push(t),this._arrFabricObject.push(i),this._visible?i.visible=!0:i.visible=!1,this.fabricCanvas.insertAt(i,a,!1)}addDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");if("viewer"===this.mode)t._setEditable(!1);else{if("editor"!==this.mode)throw new Error("Illegal 'mode'.");t._setEditable(!0)}this._addDrawingItem(t),t.updatePosition()}addDrawingItems(t){for(let e of t)this.addDrawingItem(e)}removeDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");if(!this.hasDrawingItem(t))return;if(t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,"group"===t._mediaType){const e=t.getChildDrawingItems();for(let t of e)t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,t._mapState_StyleId.clear()}else t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,t._mapState_StyleId.clear();const e=t._getFabricObject();"selected"===t.styleSelector&&(e.group?e.group.removeWithUpdate(e):this.fabricCanvas._activeObject=null,t.setState(oi.DIS_DEFAULT)),this.fabricCanvas.remove(e),this._arrDrwaingItem.splice(this._arrDrwaingItem.indexOf(t),1),this._arrFabricObject.splice(this._arrFabricObject.indexOf(e),1)}removeDrawingItems(t){for(let e of t)this.removeDrawingItem(e)}setDrawingItems(t){this.clearDrawingItems(),this.addDrawingItems(t)}getDrawingItems(t){return t&&"function"==typeof t?this._arrDrwaingItem.filter(t):Array.from(this._arrDrwaingItem)}getSelectedDrawingItems(){const t=this.fabricCanvas.getActiveObjects(),e=[];for(let i of t)this._arrFabricObject.includes(i)&&e.push(i.getDrawingItem());return e}hasDrawingItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");return this._arrDrwaingItem.includes(t)}clearDrawingItems(){this.removeDrawingItems(Array.from(this._arrDrwaingItem))}_setDefaultStyle(t,e,i){e?e.forEach(t=>t.toLowerCase()):e=Si.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Si.arrStyleSelectors;const n=Cr.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&si.DIMT_RECTANGLE&&n.push("rect"),i&si.DIMT_QUADRILATERAL&&n.push("quad"),i&si.DIMT_TEXT&&n.push("text"),i&si.DIMT_ARC&&n.push("arc"),i&si.DIMT_IMAGE&&n.push("image"),i&si.DIMT_POLYGON&&n.push("polygon"),i&si.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)}}Sr.DDN_LAYER_ID=1,Sr.DBR_LAYER_ID=2,Sr.DLR_LAYER_ID=3,Sr.USER_DEFINED_LAYER_BASE_ID=100,Sr.TIP_LAYER_ID=999;class br{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Sr(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 Tr extends Di{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Ji.set(this,void 0),$i.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e<i;e++)t+=this.getHeightOfLine(e);return t+2*this.paddingTop},this._fabricObject._getTopOffset=function(){return-this.height/2+this.getHeightOfLine(0)*(1-1/this.lineHeight)/2+this.paddingTop},this.set("backgroundColor","rgba(50, 50, 52, .8)"),this.set("lineHeight",1.3),this.set("textAlign","center")}setDuration(t){Ze(this,Ji,t,"f"),Ke(this,$i,"f")&&clearTimeout(Ke(this,$i,"f")),Ke(this,Ji,"f")>=0&&Ze(this,$i,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},Ke(this,Ji,"f")),"f")}getDuration(){return Ke(this,Ji,"f")}}Ji=new WeakMap,$i=new WeakMap;class Ir{constructor(){Qi.add(this),tn.set(this,void 0),en.set(this,void 0),nn.set(this,void 0),rn.set(this,!0),this._drawingLayerManager=new br}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=Sr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Sr.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(t<Sr.USER_DEFINED_LAYER_BASE_ID)throw new Error(`The drawing layer with id ${t} is not defined by users.`);this.deleteDrawingLayer(t)}_clearDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t)this.deleteDrawingLayer(e.getId())}clearUserDefinedDrawingLayers(){const t=this.getAllDrawingLayers();for(let e of t){const t=e.getId();t<Sr.USER_DEFINED_LAYER_BASE_ID||this.deleteUserDefinedDrawingLayer(t)}}getDrawingLayer(t){if(t==Sr.TIP_LAYER_ID)return null;return this._drawingLayerManager.getDrawingLayer(t)||([Sr.DDN_LAYER_ID,Sr.DBR_LAYER_ID,Sr.DLR_LAYER_ID].includes(t)?this._createDrawingLayer(t):null)}getAllDrawingLayers(){return this._drawingLayerManager.getAllDrawingLayers().filter(t=>t.getId()>=0&&t.getId()!==Sr.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(!(ki(e=t)&&L(e.topLeftPoint)&&ci(e.width))||e.width<=0||!ci(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ze(this,tn,JSON.parse(JSON.stringify(t)),"f"),Ke(this,tn,"f").coordinateBase||(Ke(this,tn,"f").coordinateBase="view"),Ze(this,nn,t.duration,"f"),Ke(this,Qi,"m",hn).call(this)}getTipConfig(){return Ke(this,tn,"f")?Ke(this,tn,"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()),Ze(this,rn,t,"f")}isTipVisible(){return Ke(this,rn,"f")}updateTipMessage(t){if(!Ke(this,tn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Cr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Sr.TIP_LAYER_ID)||this._createDrawingLayer(Sr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ke(this,Qi,"m",sn).call(this,t,Ke(this,tn,"f").topLeftPoint.x,Ke(this,tn,"f").topLeftPoint.y,Ke(this,tn,"f").width,Ke(this,tn,"f").coordinateBase,this._tipStyleId),Ke(this,Qi,"m",on).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ke(this,rn,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ke(this,en,"f")&&clearTimeout(Ke(this,en,"f")),Ke(this,nn,"f")>=0&&Ze(this,en,setTimeout(()=>{Ke(this,Qi,"m",an).call(this)},Ke(this,nn,"f")),"f")}}tn=new WeakMap,en=new WeakMap,nn=new WeakMap,rn=new WeakMap,Qi=new WeakSet,sn=function(t,e,i,n,r,s){const o=new Tr(t,e,i,n,s);return o.coordinateBase=r,o},on=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},an=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},hn=function(){if(!this._tip)return;const t=Ke(this,tn,"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 xr extends HTMLElement{constructor(){super(),ln.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ze(this,ln,e,"f");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 Ke(this,ln,"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())}}ln=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",xr);class Or extends Ir{static get engineResourcePath(){const t=B(jt.engineResourcePaths);return"DCV"===jt._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Or._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Or._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Or.engineResourcePath)}static async createInstance(t){const e=new Or;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Or.engineResourcePath)),await e.setUIElement(t||Or.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ke(this,yn,"f")){if(Ze(this,yn,t,"f"),Ke(this,cn,"m",Cn).call(this))Ze(this,gn,null,"f"),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"),!Ke(this,gn,"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("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ze(this,gn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ke(this,cn,"m",Cn).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 Ke(this,yn,"f")}get disposed(){return Ke(this,En,"f")}constructor(){super(),cn.add(this),un.set(this,void 0),dn.set(this,void 0),fn.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",gn.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,this._poweredBy=null,mn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,pn.set(this,!1),_n.set(this,!1),vn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ke(this,cn,"m",xn).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()&&Ke(this,cn,"m",In).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Or._onLog&&Or._onLog("window resize event triggered."),Ke(this,vn,"f").width===document.documentElement.clientWidth&&Ke(this,vn,"f").height===document.documentElement.clientHeight||(Ke(this,vn,"f").width=document.documentElement.clientWidth,Ke(this,vn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},yn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ke(this,cn,"m",Cn).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 o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.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()},wn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach(t=>Or._transformCoordinates(t,i,n,r,s,o,a));const c=new Fi({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}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ke(this,wn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case ht.CRIT_ORIGINAL_IMAGE:break;case ht.CRIT_BARCODE:m=this.getDrawingLayer(Sr.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,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Cr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ht.CRIT_TEXT_LINE:m=this.getDrawingLayer(Sr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Cr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ht.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Sr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===pt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Cr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case ht.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(Sr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===pt.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Cr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case ht.CRIT_PARSED_RESULT:case ht.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}if(t.decodedBarcodesResult)for(let e=0;e<t.decodedBarcodesResult.barcodeResultItems.length;e++)t.decodedBarcodesResult.barcodeResultItems[e].location.points.forEach(t=>Or._transformCoordinates(t,h,l,c,u,d,f));if(t.recognizedTextLinesResult)for(let e=0;e<t.recognizedTextLinesResult.textLineResultItems.length;e++)t.recognizedTextLinesResult.textLineResultItems[e].location.points.forEach(t=>Or._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult){if(t.processedDocumentResult.detectedQuadResultItems)for(let e=0;e<t.processedDocumentResult.detectedQuadResultItems.length;e++)t.processedDocumentResult.detectedQuadResultItems[e].location.points.forEach(t=>Or._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult.deskewedImageResultItems)for(let e=0;e<t.processedDocumentResult.deskewedImageResultItems.length;e++)t.processedDocumentResult.deskewedImageResultItems[e].sourceLocation.points.forEach(t=>Or._transformCoordinates(t,h,l,c,u,d,f))}}},En.set(this,!1),this.eventHandler=new Gi,this.eventHandler.on("content:updated",()=>{Ke(this,un,"f")&&clearTimeout(Ke(this,un,"f")),Ze(this,un,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),"f")}),this.eventHandler.on("videoEl:resized",()=>{Ke(this,dn,"f")&&clearTimeout(Ke(this,dn,"f")),Ze(this,dn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Xi(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),Ke(this,cn,"m",Cn).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("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ze(this,gn,t,"f");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._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||Ke(this,cn,"m",Cn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['<option class="dce-opt-gotResolution" value="got"></option>','<option data-width="1920" data-height="1080">ask 1920x1080</option>','<option data-width="1280" data-height="720">ask 1280x720</option>','<option data-width="640" data-height="480">ask 640x480</option>'].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ke(this,cn,"m",Cn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['<option class="dlr-opt-gotMinLtr" value="got"></option>','<option value="0" selected>any letter</option>','<option value="3">3+ letters</option>','<option value="5">5+ letters</option>','<option value="8">8+ letters</option>','<option value="12">12+ letters</option>','<option value="17">17+ letters</option>','<option value="30">30+ letters</option>','<option value="50">50+ letters</option>','<option value="80">80+ letters</option>','<option value="120">120+ letters</option>'].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ke(this,cn,"m",xn).call(this),Ke(this,cn,"m",Cn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ke(this,cn,"m",Cn).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;Or._onLog&&Or._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)}Ke(this,vn,"f").width=document.documentElement.clientWidth,Ke(this,vn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Ke(this,cn,"m",Cn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ke(this,cn,"m",xn).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,Ze(this,gn,null,"f"),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 Ke(this,gn,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ke(this,gn,"f"))return;if(Ke(this,gn,"f").style.objectFit=t,Ke(this,cn,"m",Cn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();Ke(this,cn,"m",On).call(this,e,i),Ke(this,cn,"m",Sn).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(Ke(this,cn,"m",Cn).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,o="contain"):(r=null===(t=Ke(this,gn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ke(this,gn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){R(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):P(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=ji.convert(this.scanRegion,t.width,t.height,this);Ze(this,mn,e,"f"),Ke(this,fn,"f")&&clearTimeout(Ke(this,fn,"f")),Ze(this,fn,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ke(this,cn,"m",Sn).call(this,t,e),Ke(this,cn,"m",On).call(this,t,e)},0),"f")}getConvertedRegion(){return Ke(this,mn,"f")}setScanRegion(t){if(null!=t&&!R(t)&&!P(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("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ke(this,gn,"f").videoWidth,i=Ke(this,gn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s<e/i?(o=s/i,a.x=Math.floor((e-r/o)/2),a.y=0,a.width=Math.ceil(r/o),a.height=i):(o=r/e,a.x=0,a.y=Math.floor((i-s/o)/2),a.width=e,a.height=Math.ceil(s/o))),null==t?void 0:t.inPixels)return a;const h=a;return h.x=Math.ceil(h.x/i*100),h.y=Math.ceil(h.y/e*100),h.width=Math.floor(h.width/e*100),h.height=Math.floor(h.height/i*100),h.isMeasuredInPercentage=!0,a}setScanRegionMask(t,e,i,n){this._drawingLayerOfMask||(this._drawingLayerOfMask=this._createDrawingLayer(-2),this.isScanRegionMaskVisible()||Ke(this,cn,"m",Tn).call(this)),this.clearScanRegionMask(),this._maskBackRectStyleId||(this._maskBackRectStyleId=Cr.createDrawingStyle({paintMode:"fill",fillStyle:this.regionMaskFillStyle,lineWidth:0})),this._maskCenterRectStyleId||(this._maskCenterRectStyleId=Cr.createDrawingStyle({paintMode:"stroke",strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth}));const r=this._drawingLayerOfMask.width,s=this._drawingLayerOfMask.height,o=new bi({x:0,y:0,width:r,height:s},this._maskBackRectStyleId),a=new bi({x:-r/2,y:-s/2+e,width:t,height:n}),h=new bi({x:-r/2+t+i,y:-s/2+e,width:r-t-i<0?0:r-t-i,height:n}),l=new bi({x:-r/2,y:-s/2,width:r,height:e}),c=new bi({x:-r/2,y:-s/2+e+n,width:r,height:s-e-n<0?0:s-e-n});a.set("strokeWidth",0),h.set("strokeWidth",0),l.set("strokeWidth",0),c.set("strokeWidth",0);const u=new Pi([a,h,l,c])._getFabricObject();o.set("clipPath",u);const d=new bi({x:t,y:e,width:i-this.regionMaskLineWidth,height:n-this.regionMaskLineWidth},this._maskCenterRectStyleId);this._drawingLayerOfMask.addDrawingItems([o,d])}clearScanRegionMask(){this._drawingLayerOfMask&&this._drawingLayerOfMask.clearDrawingItems()}deleteScanRegionMask(){this._drawingLayerOfMask&&this.deleteDrawingLayer(this._drawingLayerOfMask.getId())}_setScanRegionMaskVisible(t){Ze(this,pn,t,"f"),t?Ke(this,cn,"m",bn).call(this):Ke(this,cn,"m",Tn).call(this)}setScanRegionMaskVisible(t){this._setScanRegionMaskVisible(t),this._userSetMaskVisible=t}isScanRegionMaskVisible(){return Ke(this,pn,"f")}setScanRegionMaskStyle(t){if(!t)return;let e;t.fillStyle&&(this.regionMaskFillStyle=t.fillStyle),t.strokeStyle&&(this.regionMaskStrokeStyle=t.strokeStyle),t.lineWidth&&(this.regionMaskLineWidth=t.lineWidth),this._maskBackRectStyleId&&Cr.updateDrawingStyle(this._maskBackRectStyleId,{fillStyle:this.regionMaskFillStyle}),this._maskCenterRectStyleId&&Cr.updateDrawingStyle(this._maskCenterRectStyleId,{strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth});try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const i=this.getConvertedRegion();Ke(this,cn,"m",Sn).call(this,e,i),Ke(this,cn,"m",On).call(this,e,i)}getScanRegionMaskStyle(){return{fillStyle:this.regionMaskFillStyle,strokeStyle:this.regionMaskStrokeStyle,lineWidth:this.regionMaskLineWidth}}_setScanLaserVisible(t){Ze(this,_n,t,"f"),t?Ke(this,cn,"m",In).call(this):Ke(this,cn,"m",xn).call(this)}setScanLaserVisible(t){this._setScanLaserVisible(t),this._userSetLaserVisible=t}isScanLaserVisible(){return Ke(this,_n,"f")}_updateVideoContainer(){if(!Ke(this,gn,"f"))return;if(Ke(this,cn,"m",Cn).call(this))return;let t=1;const e=Ke(this,gn,"f").style.transform.match(/scale\((.+)\)/);e&&(t=parseFloat(e[1]));const i=this._videoContainer;if("contain"===this.videoFit&&t>1){const t=Ke(this,gn,"f").videoWidth,e=Ke(this,gn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/r<s){let t=n/s;i.style.left="0",i.style.top=(r-t)/2/r*100+"%",i.style.width="100%",i.style.height=t/r*100+"%"}else{let t=r*s;i.style.left=(n-t)/2/n*100+"%",i.style.top="0",i.style.width=t/n*100+"%",i.style.height="100%"}}else i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%"}setPowerByMessageVisible(t){this._poweredBy&&(this._poweredBy.style.display=t?"":"none",this._poweredByVisible=t);let e=this.getUIElement();e=e.shadowRoot||e;const i=e.querySelector(".dce-mn-msg-poweredby");i&&(i.style.display=t?"":"none",this._poweredByVisible=t)}isPowerByMessageVisible(){return this._poweredByVisible}updateLayers(){let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const e=this.getConvertedRegion();Ke(this,cn,"m",On).call(this,t,e),this.updateDrawingLayers(t),Ke(this,cn,"m",Sn).call(this,t,e)}clearAllInnerDrawingItems(){Ke(this,wn,"f").forEach(t=>t.remove()),Ke(this,wn,"f").length=0}dispose(){this._unbindUI(),Ze(this,En,!0,"f")}}un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,En=new WeakMap,cn=new WeakSet,Cn=function(){return"disabled"!==this._singleFrameMode},Sn=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)},bn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Tn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},In=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},xn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},On=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:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a<h?(f=s/i,l=0,c=(o-n*f)/2):(f=o/n,l=(s-i*f)/2,c=0),l+=e.x*f,c+=e.y*f,u=e.width*f,d=e.height*f;else if("cover"===r)if(a<h){f=o/n,l=e.x*f-(i*f-s)/2,l=Math.max(l,0),l=Math.min(l,s),c=e.y*f;let t=(e.x+e.width)*f-(i*f-s)/2;t=Math.max(t,0),t=Math.min(t,s),u=t-l,d=e.height*f}else{f=s/i,l=e.x*f,c=e.y*f-(n*f-o)/2,c=Math.max(c,0),c=Math.min(c,o);let t=(e.y+e.height)*f-(n*f-o)/2;t=Math.max(t,0),t=Math.min(t,o),u=e.width*f,d=t-c}else l=0,c=0,u=0,d=0;this.scanRegion?(this._divScanArea.style.left=l+this.regionMaskLineWidth*f+"px",this._divScanArea.style.top=c+this.regionMaskLineWidth*f+"px",this._divScanArea.style.width=u-this.regionMaskLineWidth*f*2+"px",this._divScanArea.style.height=d-this.regionMaskLineWidth*f*2+"px"):(this._divScanArea.style.left=l+.005*u+"px",this._divScanArea.style.top=c+.005*u+"px",this._divScanArea.style.width=u-.01*u+"px",this._divScanArea.style.height=d-.01*u+"px")},Or._defaultUIElementURL="@engineResourcePath/dce.ui.xml";class Rr{static get version(){return"4.2.3-dev-20250812165927"}static get webGLSupported(){return void 0===Rr._webGLSupported&&(Rr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),Rr._webGLSupported}get disposed(){return Ke(this,Fn,"f")}constructor(){Rn.set(this,hi.RGBA),An.set(this,null),Dn.set(this,null),Ln.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Mn.set(this,null),Fn.set(this,!1)}sourceIsReady(t){return t instanceof HTMLVideoElement?t.src?0!==t.readyState:4===t.readyState:!(t instanceof HTMLImageElement)||t.complete}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)&&!Rr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(!this.sourceIsReady(e))throw new Error("The source is not loaded.");let o;Rr._onLog&&(o=Date.now(),Rr._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(a=Math.round(r.sx)),r.sy&&(h=Math.round(r.sy)),r.sWidth&&(l=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=hi.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(!Rr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Rr._onLog&&Rr._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<u+f||_.height<d+g)&&(_.width=u+f,_.height=d+g),t.drawImage(e,a,h,l,c,u,d,f,g),Rr._onLog&&Rr._onLog("drawImage() in context2d end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:hi.RGBA,bUseWebGL:!1}}Rr._onLog&&Rr._onLog("drawImage() in WebGL.");try{(_.width<u+f||_.height<d+g)&&(_.width=u+f,_.height=d+g,_.ctxWebGL&&_.ctxWebGL.viewport(0,0,u+f,d+g));const t=_.ctxWebGL||_.getContext("webgl",{antialias:!1})||_.getContext("experimental-webgl",{antialias:!1});if(!t){Rr._onLog&&Rr._onLog("Browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");const t=new Error("Unable to get 'WebGLRenderingContext'. Your browser or machine may not support WebGL, or the canvas has already been set to a different context mode.");throw t.name="WebGLError",t}if(!_.ctxWebGL||p!==Ke(this,Rn,"f")){_.ctxWebGL=t;const e=t=>{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="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);Ze(this,Dn,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Ze(this,Ln,e(t),"f"),Ze(this,An,i(t),"f"),Ze(this,Rn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(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)},y=(t,e,o,m)=>{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,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[hi.GREY,hi.GREY32].includes(p)?1:0);let _,v,y=zi.translate(zi.identity(),-1,-1);y=zi.scale(y,2,2),y=zi.scale(y,1/t.canvas.width,1/t.canvas.height),_=zi.translate(y,u,d),_=zi.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=zi.translate(zi.identity(),1,0),v=zi.scale(v,-1,1),v=zi.translate(v,a/i,h/n),v=zi.scale(v,l/i,c/n)):(v=zi.translate(zi.identity(),a/i,h/n),v=zi.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,Ke(this,An,"f"),e),y(t,Ke(this,Dn,"f"),Ke(this,Ln,"f"),Ke(this,An,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){Rr._onLog&&Rr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Rr._onLog&&Rr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===hi.GREY?hi.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Rr._onLog&&Rr._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 o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(Rr._onLog&&(r=Date.now(),Rr._onLog("transformPixelFormat(), START: "+r)),e===i)return Rr._onLog&&Rr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[hi.RGBA,hi.RBGA,hi.GRBA,hi.GBRA,hi.BRGA,hi.BGRA];if(o.includes(e))if(i===hi.GREY){s=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4){const i=.3*t[e]+.59*t[e+1]+.11*t[e+2];s[e/4]=i}}else if(i===hi.GREY32){s=n?new Uint8Array(t):t;for(let e=0;e<t.length;e+=4){const i=.3*t[e]+.59*t[e+1]+.11*t[e+2];s[e]=i,s[e+1]=i,s[e+2]=i}}else{if(!o.includes(i))throw new Error("Unable to transform.");if(n){s=new Uint8Array(t);const n=e.indexOf("r"),r=e.indexOf("g"),o=e.indexOf("b"),a=i.indexOf("r"),h=i.indexOf("g"),l=i.indexOf("b");for(let e=0;e<t.length;e+=4)s[e+a]=t[e+n],s[e+h]=t[e+r],s[e+l]=t[e+o]}else{s=t;const n=e.indexOf("r"),r=e.indexOf("g"),o=e.indexOf("b"),a=i.indexOf("r"),h=i.indexOf("g"),l=i.indexOf("b");for(let e=0;e<t.length;e+=4){let i=[t[e],t[e+1],t[e+2]];s[e+a]=i[n],s[e+h]=i[r],s[e+l]=i[o]}}}else if(e===hi.GREY){if(i!==hi.GREY32)throw new Error("Unable to transform.");s=new Uint8Array(4*t.length);for(let e=0;e<t.length;e++)s[4*e]=t[e],s[4*e+1]=t[e],s[4*e+2]=t[e],s[4*e+3]=255}else{if(e!==hi.GREY32)throw new Error("Unable to transform.");if(i!==hi.GREY)throw new Error("Unable to transform.");s=new Uint8Array(t.length/4);for(let e=0;e<t.length;e+=4)s[e/4]=t[e]}return Rr._onLog&&Rr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),s}getImageData(t,e,i){var n,r,s,o,a;if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!this.sourceIsReady(t))throw new Error("The source is not loaded.");let h,l;if(t instanceof HTMLImageElement)h=t.naturalWidth,l=t.naturalHeight;else if(t instanceof HTMLCanvasElement)h=t.width,l=t.height;else if(t instanceof HTMLVideoElement)h=t.videoWidth,l=t.videoHeight;else{if(!(t instanceof ImageBitmap))throw Error("The type of 'source' is not supported.");h=t.width,l=t.height}let c,u=Rr.webGLSupported&&this.useWebGLByDefault;if(e.sx<0||e.sy<0||e.sx+e.sWidth>h||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=Rr._onLog)||void 0===n||n.call(Rr,"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)||hi.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(hi.GREY===y&&w.length<p*_||hi.RGBA===y&&w.length<p*_*4))throw new Error("Unexpected size of the 'bufferContainer'.");if(u){null===(r=Rr._onLog)||void 0===r||r.call(Rr,"getImageData() in WebGL.");let o,a=this._reusedWebGLCvs=this._reusedWebGLCvs||document.createElement("canvas");try{if(w)if(y===hi.GREY){if(v=new Uint8Array(4*p*_),o=this.drawImage(a,t,h,l,{sx:d,sy:f,sWidth:g,sHeight:m,dWidth:p,dHeight:_},{pixelFormat:y,bUseWebGL:!0,bufferContainer:v,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),v=this.transformPixelFormat(v,o.pixelFormat,y),w){if(w.length<v.length)throw new Error("Unexpected size of the 'bufferContainer'.");w.set(v)}}else o=this.drawImage(a,t,h,l,{sx:d,sy:f,sWidth:g,sHeight:m,dWidth:p,dHeight:_},{pixelFormat:y,bUseWebGL:!0,bufferContainer:w,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),v=new Uint8Array(w.buffer,0,4*p*_),v=this.transformPixelFormat(v,o.pixelFormat,y);else y===hi.GREY?((!Ke(this,Mn,"f")||Ke(this,Mn,"f").length<4*p*_)&&Ze(this,Mn,new Uint8Array(4*p*_),"f"),v=new Uint8Array(Ke(this,Mn,"f").buffer,0,4*p*_)):v=new Uint8Array(4*p*_),o=this.drawImage(a,t,h,l,{sx:d,sy:f,sWidth:g,sHeight:m,dWidth:p,dHeight:_},{pixelFormat:y,bUseWebGL:!0,bufferContainer:v,isEnableMirroring:null==i?void 0:i.isEnableMirroring}),v=this.transformPixelFormat(v,o.pixelFormat,y)}catch(n){if("WebGLError"===n.name)return this.forceLoseContext(),console.warn("WebGLError: "+(null==n?void 0:n.message)),null===(s=Rr._onLog)||void 0===s||s.call(Rr,"getImageData() in WebGL failed, try again in context2d."),Rr._webGLSupported=!1,this.getImageData(t,e,i);throw n}}else{null===(o=Rr._onLog)||void 0===o||o.call(Rr,"getImageData() in context2d.");let e=this._reusedCvs=this._reusedCvs||document.createElement("canvas");e.width!=p&&(e.width=p),e.height!=_&&(e.height=_);let n=e.getContext("2d",{willReadFrequently:!0});if(i.isEnableMirroring?(n.save(),n.translate(p,0),n.scale(-1,1),n.drawImage(t,d,f,g,m,0,0,p,_),n.restore()):n.drawImage(t,d,f,g,m,0,0,p,_),v=new Uint8Array(n.getImageData(0,0,p,_).data.buffer),hi.GREY===y){let t=w||new Uint8Array(p*_);for(let e=0;e<v.length;e+=4)t[e/4]=Math.round((v[e]+v[e+1]+v[e+2])/3);v=t}else null==w||w.set(v)}return null===(a=Rr._onLog)||void 0===a||a.call(Rr,"getImageData() end. Costs: "+(Date.now()-c)),{data:v,pixelFormat:y,width:p,height:_,bUseWebGL:u}}convertDataToCvs(t,e,i,n){if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new TypeError("Invalid 'data'.");if("number"!=typeof e||e<=0)throw new Error("Invalid 'width'.");if("number"!=typeof i||i<=0)throw new Error("Invalid 'height'.");const r=document.createElement("canvas");let s;if(r.width=e,r.height=i,n===hi.GREY){s=new Uint8ClampedArray(4*e*i);for(let e=0;e<s.length;e+=4)s[e]=t[e/4],s[e+1]=t[e/4],s[e+2]=t[e/4],s[e+3]=255}else s=new Uint8ClampedArray(t.buffer);const o=new ImageData(s,e,i);return r.getContext("2d").putImageData(o,0,0),r}forceLoseContext(){var t;if(!this._reusedWebGLCvs)return;const e=this._reusedWebGLCvs.ctxWebGL;e&&!e.isContextLost()&&(null===(t=e.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext()),Ze(this,An,null,"f"),Ze(this,Dn,null,"f"),Ze(this,Ln,null,"f"),this._reusedWebGLCvs=null}dispose(){this.forceLoseContext(),Ze(this,Fn,!0,"f")}}Rn=new WeakMap,An=new WeakMap,Dn=new WeakMap,Ln=new WeakMap,Mn=new WeakMap,Fn=new WeakMap;const Ar=(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 Dr{static get version(){return"4.2.3-dev-20250812165927"}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 o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(qe.OS))return Dr.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(qe.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 o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(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)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(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(!Ke(this,qn,"f"))return"closed";if("pending"===Ke(this,qn,"f"))return"opening";if("fulfilled"===Ke(this,qn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Dr.isStorageAvailable("localStorage")?Ze(this,Yn,!0,"f"):(Ze(this,Yn,!1,"f"),console.warn("Local storage is unavailable")):Ze(this,Yn,!1,"f")}get ifSaveLastUsedCamera(){return Ke(this,Yn,"f")}get isVideoPlaying(){return!(!Ke(this,Nn,"f")||Ke(this,Nn,"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=Ke(this,tr,"f"))||void 0===e||e.removeEventListener("click",Ke(this,Qn,"f")),null===(i=Ke(this,tr,"f"))||void 0===i||i.removeEventListener("touchend",Ke(this,Qn,"f")),null===(n=Ke(this,tr,"f"))||void 0===n||n.removeEventListener("touchmove",Ke(this,$n,"f")),Ze(this,tr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(qe.OS)?(t.addEventListener("touchend",Ke(this,Qn,"f")),t.addEventListener("touchmove",Ke(this,$n,"f"))):t.addEventListener("click",Ke(this,Qn,"f")))}get tapFocusEventBoundEl(){return Ke(this,tr,"f")}get disposed(){return Ke(this,lr,"f")}constructor(t){var e,i;kn.add(this),Nn.set(this,null),Bn.set(this,void 0),this._zoomPreSetting=null,jn.set(this,()=>{"opened"===this.state&&Ke(this,rr,"f").fire("resumed",null,{target:this,async:!1})}),Un.set(this,()=>{Ke(this,rr,"f").fire("paused",null,{target:this,async:!1})}),Vn.set(this,void 0),Gn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Wn.set(this,void 0),Yn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,Hn.set(this,void 0),Xn.set(this,!0),zn.set(this,void 0),qn.set(this,void 0),Kn.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},Zn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Ke(this,Nn,"f")).objectFit,s=this.getResolution(),o=Ke(this,Nn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Ke(this,Nn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},Jn.set(this,!1),$n.set(this,()=>{Ze(this,Jn,!0,"f")}),Qn.set(this,async t=>{var e;if(Ke(this,Jn,"f"))return void Ze(this,Jn,!1,"f");if(!Ke(this,Zn,"f"))return;if(!this.isVideoPlaying)return;if(!Ke(this,Bn,"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 o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Dr._onLog&&(c=Date.now());try{await Ke(this,kn,"m",yr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Dr._onLog)throw Dr._onLog(t),t}Dr._onLog&&Dr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Dr._onLog&&Dr._onLog("Back to continuous focus."),null===(t=Ke(this,Bn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),Ke(this,rr,"f").fire("tapfocus",null,{target:this,async:!1})}),tr.set(this,null),er.set(this,1),ir.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Ke(this,Nn,"f"))return;const t=Ke(this,er,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Ke(this,Nn,"f").style.transform="";else{const e=window.getComputedStyle(Ke(this,Nn,"f")).objectFit,i=Ke(this,Nn,"f").videoWidth,n=Ke(this,Nn,"f").videoHeight,{width:r,height:s}=Ke(this,Nn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=o<a?r/(i/t):s/(n/t):"cover"===e&&(h=a>o?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-Ke(this,ir,"f").x),c=h*(1-1/t)*(n/2-Ke(this,ir,"f").y);Ke(this,Nn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},nr.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===hi.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.data[t/4],e[t+1]=this.data[t/4],e[t+2]=this.data[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.data.buffer);const i=new ImageData(e,this.width,this.height);return t.getContext("2d").putImageData(i,0,0),t}),rr.set(this,void 0),sr.set(this,["before:open","opened","before:close","closed","before:camera:change","camera:changed","before:resolution:change","resolution:changed","played","paused","resumed","tapfocus"]),this.detectedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],or.set(this,new Map),ar.set(this,!1),hr.set(this,async()=>{var t,e;if("visible"===document.visibilityState){if(Dr._onLog&&Dr._onLog("document visible. video paused: "+(null===(t=Ke(this,Nn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Dr._onLog&&Dr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Dr._onLog&&Dr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Ke(this,kn,"m",gr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Dr._onLog&&Dr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Dr._onLog&&Dr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Ke(this,kn,"m",gr).call(this)}}}else"hidden"===document.visibilityState&&(Dr._onLog&&Dr._onLog("document hidden. video paused: "+(null===(e=Ke(this,Nn,"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(()=>{Dr.onWarning&&Dr.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),Ze(this,rr,new Gi,"f"),this.imageDataGetter=new Rr,document.addEventListener("visibilitychange",Ke(this,hr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Ke(this,jn,"f")),t.addEventListener("pause",Ke(this,Un,"f")),Ze(this,Nn,t,"f")}getVideoEl(){return Ke(this,Nn,"f")}releaseVideoEl(){var t,e;null===(t=Ke(this,Nn,"f"))||void 0===t||t.removeEventListener("play",Ke(this,jn,"f")),null===(e=Ke(this,Nn,"f"))||void 0===e||e.removeEventListener("pause",Ke(this,Un,"f")),Ze(this,Nn,null,"f")}isVideoLoaded(){return!!Ke(this,Nn,"f")&&(this.videoSrc?0!==Ke(this,Nn,"f").readyState:4===Ke(this,Nn,"f").readyState)}async open(){if(Ke(this,zn,"f")&&!Ke(this,Xn,"f")){if("pending"===Ke(this,qn,"f"))return Ke(this,zn,"f");if("fulfilled"===Ke(this,qn,"f"))return}Ke(this,rr,"f").fire("before:open",null,{target:this}),await Ke(this,kn,"m",gr).call(this),Ke(this,rr,"f").fire("played",null,{target:this,async:!1}),Ke(this,rr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Ke(this,rr,"f").fire("before:close",null,{target:this});const t=Ke(this,zn,"f");if(Ke(this,kn,"m",pr).call(this),t&&"pending"===Ke(this,qn,"f")){try{await t}catch(t){}if(!1===Ke(this,Xn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Ze(this,zn,null,"f"),Ze(this,qn,null,"f"),Ke(this,rr,"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.");Ke(this,Nn,"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 Ke(this,Nn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Ke(this,Vn,"f").video&&(Ke(this,Vn,"f").video={}),delete Ke(this,Vn,"f").video.facingMode,Ke(this,Vn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ke(this,Xn,"f"))){Ke(this,rr,"f").fire("before:camera:change",[],{target:this,async:!1}),await Ke(this,kn,"m",mr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ke(this,Gn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Ke(this,Vn,"f").video&&(Ke(this,Vn,"f").video={}),(null==t?void 0:t.resolution)&&(Ke(this,Vn,"f").video.width={ideal:t.resolution.width},Ke(this,Vn,"f").video.height={ideal:t.resolution.height}),delete Ke(this,Vn,"f").video.deviceId,Ke(this,Vn,"f").video.facingMode={exact:"user"},Ze(this,Wn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ke(this,Xn,"f"))){Ke(this,rr,"f").fire("before:camera:change",[],{target:this,async:!1}),Ke(this,kn,"m",mr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ke(this,Gn,"f")}}getCamera(){var t;if(Ke(this,Gn,"f"))return Ke(this,Gn,"f");{let e=(null===(t=Ke(this,Vn,"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)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}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<n.length;t++){let e,i=n[t];for(let t of s)if(i.deviceId==t.deviceId){e=t;break}e||(e={deviceId:i.deviceId,label:i.label?i.label:"camera "+t,_checked:!1}),e.deviceId&&r.push(e)}return this._arrCameras=r,Dr._onLog&&Dr._onLog(JSON.stringify(this._arrCameras)),r}async getCameras(){var t,e;if(!(null===(e=null===(t=null===window||void 0===window?void 0:window.navigator)||void 0===t?void 0:t.mediaDevices)||void 0===e?void 0:e.enumerateDevices))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");const i=(await navigator.mediaDevices.enumerateDevices()).filter(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 Ke(this,Vn,"f").video&&(Ke(this,Vn,"f").video={}),i?(Ke(this,Vn,"f").video.width={exact:t},Ke(this,Vn,"f").video.height={exact:e}):(Ke(this,Vn,"f").video.width={ideal:t},Ke(this,Vn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Ke(this,Xn,"f"))return null;Ke(this,rr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Ke(this,kn,"m",mr).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&&Ke(this,Nn,"f"))return{width:Ke(this,Nn,"f").videoWidth,height:Ke(this,Nn,"f").videoHeight};if(Ke(this,Bn,"f")){const t=Ke(this,Bn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Ke(this,Nn,"f").videoWidth,height:Ke(this,Nn,"f").videoHeight};{const t={width:0,height:0};let e=Ke(this,Vn,"f").video.width||0,i=Ke(this,Vn,"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,o,a,h,l,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=Ke(this,or,"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=Ke(this,Gn,"f"))||void 0===u?void 0:u.deviceId;let e=Ke(this,or,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Ke(this,or,"f").set(d,e),Ze(this,Kn,!0,"f");try{for(let t of this.detectedResolutions){await Ke(this,Bn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Ke(this,kn,"m",ur).call(this);const i=Ke(this,Bn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Ke(this,kn,"m",pr).call(this),Ze(this,Kn,!1,"f"),t}try{await Ke(this,kn,"m",gr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Ze(this,Kn,!1,"f")}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 o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=Ke(this,Vn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Ke(this,Vn,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Ke(this,Vn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Ke(this,or,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Ke(this,or,"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'.");Ze(this,Vn,JSON.parse(JSON.stringify(t)),"f"),Ze(this,Wn,null,"f"),e&&await Ke(this,kn,"m",mr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Ke(this,Vn,"f")))}resetMediaStreamConstraints(){Ze(this,Vn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ke(this,Bn,"f").getCapabilities?Ke(this,Bn,"f").getCapabilities():{}}getCameraSettings(){if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ke(this,Bn,"f").getSettings()}async turnOnTorch(){if(!Ke(this,Bn,"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 Ke(this,Bn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Ke(this,Bn,"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 Ke(this,Bn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ke(this,Bn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=Ar(t,n.min,n.step,n.max)),await Ke(this,Bn,"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(!Ke(this,Bn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=Ar(t,n.min,n.step,n.max)),await Ke(this,Bn,"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(!Ke(this,Bn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max));const r=this.getResolution();return await Ke(this,Bn,"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(!Ke(this,Bn,"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&&(i<r.min?i=r.min:i>r.max&&(i=r.max),i=Ar(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Ke(this,Bn,"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 Ke(this,kn,"m",yr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Ke(this,Bn,"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}enableTapToFocus(){Ze(this,Zn,!0,"f")}disableTapToFocus(){Ze(this,Zn,!1,"f")}isTapToFocusEnabled(){return Ke(this,Zn,"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){t.centerPoint?Ke(this,kn,"m",wr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Ke(this,kn,"m",Er).call(this,Ke(this,ir,"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)}}else this._zoomPreSetting=t}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*Ke(this,er,"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(!Ke(this,Bn,"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&&(t<n.min?t=n.min:t>n.max&&(t=n.max),t=Ar(t,n.min,n.step,n.max)),await Ke(this,Bn,"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&&Ke(this,kn,"m",wr).call(this,e),Ze(this,er,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Ke(this,er,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Ze(this,ir,{x:t.width/2,y:t.height/2},"f")}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(Ke(this,Kn,"f"))return null;const e=Date.now();Dr._onLog&&Dr._onLog("getFrameData() START: "+e);const i=Ke(this,Nn,"f").videoWidth,n=Ke(this,Nn,"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=hi.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Ke(this,er,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Ke(this,ir,"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.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(Ke(this,Nn,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Dr._onLog&&Dr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Ke(this,nr,"f")}}on(t,e){if(!Ke(this,sr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Ke(this,rr,"f").on(t,e)}off(t,e){Ke(this,rr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Ke(this,rr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Ke(this,hr,"f")),Ze(this,lr,!0,"f")}}var Lr,Mr,Fr,Pr,kr,Nr,Br,jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs;Nn=new WeakMap,Bn=new WeakMap,jn=new WeakMap,Un=new WeakMap,Vn=new WeakMap,Gn=new WeakMap,Wn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,kn=new WeakSet,cr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Ke(this,Wn,"f"))delete t.video.facingMode,t.video.deviceId={exact:Ke(this,Wn,"f")};else if(this.ifSaveLastUsedCamera&&Dr.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(qe.OS)?(await this._getCameras(!1),Ke(this,kn,"m",ur).call(this),e=Dr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(qe.OS)||(await this._getCameras(!1),Ke(this,kn,"m",ur).call(this),e=Dr.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},ur=function(){if(Ke(this,Xn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},dr=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{Dr._onLog&&Dr._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)),Ke(this,kn,"m",ur).call(this));try{Dr._onLog&&Dr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Ke(this,kn,"m",ur).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Dr._onLog&&Dr._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)){const t=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let e of t){const t={video:{deviceId:{ideal:e.deviceId},facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}}};if(await r(t),n)break}}if(!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}},fr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),Ze(this,Bn,null,"f")},gr=async function(){Ze(this,Xn,!1,"f");const t=Ze(this,Hn,Symbol(),"f");if(Ke(this,zn,"f")&&"pending"===Ke(this,qn,"f")){try{await Ke(this,zn,"f")}catch(t){}Ke(this,kn,"m",ur).call(this)}if(t!==Ke(this,Hn,"f"))return;const e=Ze(this,zn,(async()=>{Ze(this,qn,"pending","f");try{if(this.videoSrc){if(!Ke(this,Nn,"f"))throw new Error("'videoEl' should be set.");await Dr.playVideo(Ke(this,Nn,"f"),this.videoSrc,this.cameraOpenTimeout),Ke(this,kn,"m",ur).call(this)}else{let t=await Ke(this,kn,"m",cr).call(this);Ke(this,kn,"m",fr).call(this);let e=await Ke(this,kn,"m",dr).call(this,t);await this._getCameras(!1),Ke(this,kn,"m",ur).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=Ke(this,Vn,"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),!(Ke(this,Wn,"f")||this.ifSaveLastUsedCamera&&Dr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Dr.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 Ke(this,kn,"m",dr).call(this,t),Ke(this,kn,"m",ur).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Ze(this,Wn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Dr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Ke(this,Wn,"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))))),Ke(this,Nn,"f")&&(await Dr.playVideo(Ke(this,Nn,"f"),e,this.cameraOpenTimeout),Ke(this,kn,"m",ur).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Ze(this,Bn,s[0],"f"),Ze(this,Gn,r,"f")}}catch(t){throw Ke(this,kn,"m",pr).call(this),Ze(this,qn,null,"f"),t}Ze(this,qn,"fulfilled","f")})(),"f");return e},mr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Ke(this,Gn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Ke(this,kn,"m",gr).call(this);const n=this.getResolution();e&&e!==Ke(this,Gn,"f").deviceId&&Ke(this,rr,"f").fire("camera:changed",[Ke(this,Gn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Ke(this,rr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Ke(this,rr,"f").fire("played",null,{target:this,async:!1})},pr=function(){Ke(this,kn,"m",fr).call(this),Ze(this,Gn,null,"f"),Ke(this,Nn,"f")&&(Ke(this,Nn,"f").srcObject=null,this.videoSrc&&(Ke(this,Nn,"f").pause(),Ke(this,Nn,"f").currentTime=0)),Ze(this,Xn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},_r=async function t(e,i){const n=t=>{if(!Ke(this,Bn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Ke(this,Bn,"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=Ar(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Ke(this,Bn,"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,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;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(Ke(this,Nn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:hi.RGBA,bufferContainer:d}))return Ke(this,kn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;t<e;++t){let e=f[t]-f[t+8];++t;let i=f[t]-f[t+8];++t;let n=f[t]-f[t+8];++t,g+=e*e+i*i+n*n}return-g},vr=async function t(e,i,n,r,s,o,a){let h;if(i=Ar(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ar(r,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o?o=Ar(o,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max):(o=Ar(Math.sqrt((i||this._focusParameters.fds.step)*(r||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Ke(this,kn,"m",_r).call(this,e,o)),a<=n&&a<=s?h=3:n<s&&n<a?h=1:s<n&&s<a&&(h=2),(r-i)/2<=this._focusParameters.fds.step)return 3===h||(1===h?await Ke(this,Bn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}):2===h&&await Ke(this,Bn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:r}]})),!0;if(1===h)return await Ke(this,kn,"m",t).call(this,e,i,n,o,a);if(2===h)return await Ke(this,kn,"m",t).call(this,e,o,a,r,s);if(3!==h)return n=await Ke(this,kn,"m",_r).call(this,e,i),s=await Ke(this,kn,"m",_r).call(this,e,r),await Ke(this,kn,"m",t).call(this,e,i,n,r,s);let l=Ar(Math.sqrt((i||this._focusParameters.fds.step)*(o||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),c=Ar(Math.sqrt((r||this._focusParameters.fds.step)*(o||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max);if(Math.abs(1/this._focusParameters.oldDistance-1/l)<=Math.abs(1/this._focusParameters.oldDistance-1/c)){let h=await Ke(this,kn,"m",_r).call(this,e,l);if(h<a)return await Ke(this,kn,"m",t).call(this,e,i,n,o,a,l,h);if(h==a)return await Ke(this,kn,"m",t).call(this,e,l,h,o,a);let u=await Ke(this,kn,"m",_r).call(this,e,c);if(h>a&&a<u)return await Ke(this,kn,"m",t).call(this,e,l,h,c,u,o,a);if(a==u)return await Ke(this,kn,"m",t).call(this,e,o,a,c,u);if(a>u)return await Ke(this,kn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await Ke(this,kn,"m",_r).call(this,e,c);if(a>h)return await Ke(this,kn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await Ke(this,kn,"m",t).call(this,e,o,a,c,h);let u=await Ke(this,kn,"m",_r).call(this,e,l);if(u>a&&a<h)return await Ke(this,kn,"m",t).call(this,e,l,u,c,h,o,a);if(u==a)return await Ke(this,kn,"m",t).call(this,e,l,u,o,a);if(u<a)return await Ke(this,kn,"m",t).call(this,e,i,n,o,a,l,u)}return!1},yr=async function(t,e,i,n,r){var s;if(1==this._focusParameters.isDoingFocus)return!1;if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'centerPoint'.");if(!e||"string"!=typeof e)throw new Error("Invalid 'width'.");if(!i||"string"!=typeof i)throw new Error("Invalid 'height'.");const o=this.getResolution();let a=0,h=0;if(t.x.endsWith("px"))a=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid 'centerPoint'.");a=parseFloat(t.x)/100*o.width}if(t.y.endsWith("px"))h=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid 'centerPoint'.");h=parseFloat(t.y)/100*o.height}if(isNaN(a)||isNaN(h)||a<0||a>o.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<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*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Ke(this,er,"f")){const t=Ke(this,er,"f"),e=Ke(this,ir,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/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:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||e<this._focusParameters.fds.min)&&(e=this._focusParameters.fds.min),(null==i||i>this._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Ar(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ar(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ar(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Ke(this,kn,"m",_r).call(this,t,s),a=await Ke(this,kn,"m",_r).call(this,t,r),h=await Ke(this,kn,"m",_r).call(this,t,n);if(a>h&&h<o){const e=await Ke(this,kn,"m",vr).call(this,t,r,a,s,o,n,h);return this._focusParameters.isDoingFocus=0,e}if(a<h&&a<o){let i=await Ke(this,kn,"m",_r).call(this,t,e);const s=await Ke(this,kn,"m",vr).call(this,t,e,i,n,h,r,a);return this._focusParameters.isDoingFocus=0,s}if(h>o&&a>o){let e=await Ke(this,kn,"m",_r).call(this,t,i);const r=await Ke(this,kn,"m",vr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&h<o){const e=await Ke(this,kn,"m",vr).call(this,t,r,a,n,h);return this._focusParameters.isDoingFocus=0,e}if(h==o&&a>h){const e=await Ke(this,kn,"m",vr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,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.");Ze(this,ir,{x:i,y:n},"f")},Er=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},Dr.browserInfo=qe,Dr.onWarning=null===(Pn=null===window||void 0===window?void 0:window.console)||void 0===Pn?void 0:Pn.warn;class gs{constructor(t){Lr.add(this),Mr.set(this,void 0),Fr.set(this,0),Pr.set(this,void 0),kr.set(this,0),Nr.set(this,!1),Ze(this,Mr,t,"f")}startCharging(){Ke(this,Nr,"f")||(gs._onLog&&gs._onLog("start charging."),Ke(this,Lr,"m",jr).call(this),Ze(this,Nr,!0,"f"))}stopCharging(){Ke(this,Pr,"f")&&clearTimeout(Ke(this,Pr,"f")),Ke(this,Nr,"f")&&(gs._onLog&&gs._onLog("stop charging."),Ze(this,Fr,Date.now()-Ke(this,kr,"f"),"f"),Ze(this,Nr,!1,"f"))}}Mr=new WeakMap,Fr=new WeakMap,Pr=new WeakMap,kr=new WeakMap,Nr=new WeakMap,Lr=new WeakSet,Br=function(){jt.cfd(1),gs._onLog&&gs._onLog("charge 1.")},jr=function t(){0==Ke(this,Fr,"f")&&Ke(this,Lr,"m",Br).call(this),Ze(this,kr,Date.now(),"f"),Ke(this,Pr,"f")&&clearTimeout(Ke(this,Pr,"f")),Ze(this,Pr,setTimeout(()=>{Ze(this,Fr,0,"f"),Ke(this,Lr,"m",t).call(this)},Ke(this,Mr,"f")-Ke(this,Fr,"f")),"f")};class ms{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ke(this,Ur,"f",Wr)<100)){if(Ze(this,Ur,e,"f",Wr),Ke(this,Ur,"f",Vr).size&&(t=Ke(this,Ur,"f",Vr).values().next().value,this.beepSoundSource==t.src?(Ke(this,Ur,"f",Vr).delete(t),t.play()):t=null),!t)if(Ke(this,Ur,"f",Gr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{Ke(this,Ur,"f",Gr).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ke(this,Ur,"f",Gr).delete(t),Ke(this,Ur,"f",Vr).add(t)})}else Ke(this,Ur,"f",Yr)||(Ze(this,Ur,!0,"f",Yr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ke(this,Ur,"f",Gr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(ms.vibrateDuration)}}}Ur=ms,Vr={value:new Set},Gr={value:new Set},Wr={value:0},Yr={value:!1},ms.allowBeep=!0,ms.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",ms.allowVibrate=!0,ms.vibrateDuration=300;const ps=new Map([[hi.GREY,v.IPF_GRAYSCALED],[hi.RGBA,v.IPF_ABGR_8888]]),_s="function"==typeof BigInt?t=>BigInt(t):t=>t,vs=(_s("0x00"),_s("0xFFFFFFFFFFFFFFFF"),_s("0xFE3BFFFF"),_s("0x003007FF")),ys=(_s("0x0003F800"),_s("0x1"),_s("0x2"),_s("0x4"),_s("0x8"),_s("0x10"),_s("0x20"),_s("0x40"),_s("0x80"),_s("0x100"),_s("0x200"),_s("0x400"),_s("0x800"),_s("0x1000"),_s("0x2000"),_s("0x4000"),_s("0x8000"),_s("0x10000"),_s("0x20000"),_s("0x00040000"),_s("0x01000000"),_s("0x02000000"),_s("0x04000000")),ws=_s("0x08000000");_s("0x10000000"),_s("0x20000000"),_s("0x40000000"),_s("0x00080000"),_s("0x80000000"),_s("0x100000"),_s("0x200000"),_s("0x400000"),_s("0x800000"),_s("0x1000000000"),_s("0x3F0000000000000"),_s("0x100000000"),_s("0x10000000000000"),_s("0x20000000000000"),_s("0x40000000000000"),_s("0x80000000000000"),_s("0x100000000000000"),_s("0x200000000000000"),_s("0x200000000"),_s("0x400000000"),_s("0x800000000"),_s("0xC00000000"),_s("0x2000000000"),_s("0x4000000000");class Es extends nt{static set _onLog(t){Ze(Es,Xr,t,"f",zr),Dr._onLog=t,gs._onLog=t}static get _onLog(){return Ke(Es,Xr,"f",zr)}static async detectEnvironment(){return await(async()=>({wasm:Je,worker:$e,getUserMedia:Qe,camera:await ti(),browser:qe.browser,version:qe.version,OS:qe.OS}))()}static async testCameraAccess(){const t=await Dr.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 Or))throw new TypeError("Invalid view.");if(!Es._isRTU&&(null===(e=kt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=kt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await jt.loadWasm(),await kt.license.dynamsoft()}const n=new Es(t);return Es.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{Es.onWarning&&Es.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(()=>{Es.onWarning&&Es.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 isEnableMirroring(){return this._isEnableMirroring}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.");Ze(this,Jr,t,"f")}get singleFrameMode(){return Ke(this,Jr,"f")}get _isFetchingStarted(){return Ke(this,ns,"f")}get disposed(){return Ke(this,hs,"f")}constructor(t){if(super(),Hr.add(this),qr.set(this,"closed"),Kr.set(this,void 0),Zr.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,Jr.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()},$r.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},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;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 a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?hi.GREY:hi.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===hi.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:ps.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:ft.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:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:Ke(this,Qr,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():ji.convert(Ke(this,es,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ke(this,$r,"f").call(this,t,t.width,t.height,e);Ke(this,Kr,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},Qr.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===v.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t<e.length;t+=4)e[t]=this.bytes[t/4],e[t+1]=this.bytes[t/4],e[t+2]=this.bytes[t/4],e[t+3]=255}else e=new Uint8ClampedArray(this.bytes.buffer);return t.getContext("2d").putImageData(new ImageData(e,this.width,this.height),0,0),t}),ts.set(this,void 0),es.set(this,void 0),is.set(this,v.IPF_ABGR_8888),ns.set(this,!1),this._imageId=-1,rs.set(this,void 0),this.fetchInterval=0,ss.set(this,{enhancedFocus:!1,autoZoom:!1,tapToFocus:!1}),os.set(this,{minValue:1,maxValue:999,autoFocusFrameArray:[],autoFocusFrameLimit:[5,3],autoZoomDetectionArea:.5,autoZoomTargetBorder:.9,autoZoomIdealArea:[0,.05],autoZoomInFrameArray:[],autoZoomInFrameLimit:[5,3],autoZoomInMaxTimes:5,autoZoomInMinStep:Math.pow(10,.2),autoZoomInIdealModuleSize:6,autoZoomOutFrameCount:0,autoZoomOutFrameLimit:3,autoZoomOutStepRate:1/3,autoZoomOutStepRate_2:.05,autoZoomOutMinStep:2,frameArrayInIdealZoom:[],frameLimitInIdealZoom:[5,3]}),as.set(this,void 0),hs.set(this,!1),this.isCameraEnhancer=!0,this._taskid4AutoTorch=null,this._delay4AutoTorch=250,this.grayThreshold4AutoTorch=20,this.maxDarkCount4AutoTroch=3,t&&!(t instanceof Or))throw new TypeError("Invalid view.");Ze(this,Kr,new Gi,"f"),this.cameraManager=new Dr,this._imageDataGetter=this.cameraManager.imageDataGetter,this.cameraManager.updateVideoElWhenSoftwareScaled=()=>{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(qe.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",()=>{Ke(this,as,"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",()=>{Ke(this,as,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{Ke(this,ss,"f").tapToFocus&&Ke(this,as,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(Ke(this,Hr,"m",ls).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Es._onLog&&(Es._onLog("intermediateResultUnits:"),Es._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===_t.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===_t.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Es._onLog&&(Es._onLog("hasLocalizedBarcodes:"),Es._onLog(h)),Ke(this,ss,"f").autoZoom||Ke(this,ss,"f").enhancedFocus)if(a)Ke(this,os,"f").autoZoomInFrameArray.length=0,Ke(this,os,"f").autoZoomOutFrameCount=0,Ke(this,os,"f").frameArrayInIdealZoom.length=0,Ke(this,os,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ke(this,ss,"f").autoZoom&&Ke(this,as,"f").startCharging()},a=async t=>{await this.setFocus(t),Ke(this,ss,"f").enhancedFocus&&Ke(this,as,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Ke(this,os,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ke(this,os,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Ke(this,os,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ke(this,os,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Es._onLog&&(Es._onLog("detectionArea:"),Es._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;s<r;s++){const o=t[s],a=t[(s+1)%r];if(Wi(o,a,{x:e,y:i}))return!0;Yi(o.y-i)>0!=Yi(a.y-i)>0&&Yi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Hi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Hi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Hi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Hi([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 o)if(e.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Or._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Es._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Cr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===_t.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(Es._onLog&&(Es._onLog("intersectedResults:"),Es._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==ys||t.possibleFormats==ws);if(t.length||(t=s.filter(t=>t.possibleFormats==vs),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)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n<t.length;n++){const r=e(t[n]);(t[n].confidence>1.1*a.confidence||t[n].confidence>.9*a.confidence&&r<i)&&(a=t[n],i=r)}}}if(Es._onLog&&(Es._onLog("highPriorityResult:"),Es._onLog(a)),a){const r=a.location.points;t=Math.min(r[0].x,r[1].x,r[2].x,r[3].x),e=Math.max(r[0].x,r[1].x,r[2].x,r[3].x),i=Math.min(r[0].y,r[1].y,r[2].y,r[3].y),n=Math.max(r[0].y,r[1].y,r[2].y,r[3].y),m={points:[{x:t,y:i},{x:e,y:i},{x:e,y:n},{x:t,y:n}],result:a}}}if(Es._onLog&&(Es._onLog("boundingRect:"),Es._onLog(m)),!m)return;if(Es._debug&&this.cameraView&&(null==m?void 0:m.points)){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99)),e=this.__styleId1||(this.__styleId1=Cr.createDrawingStyle({strokeStyle:"blue"})),i=new Ri({points:m.points},e);t.addDrawingItems([i])}if(Ke(this,os,"f").autoZoomOutFrameCount=0,Ke(this,ss,"f").autoZoom){const i=Ke(this,os,"f").autoZoomIdealArea[1];let n=(1-Ke(this,os,"f").autoZoomTargetBorder)/2;const r=m.points[0].x/u,s=(u-m.points[2].x)/u,o=m.points[0].y/d,h=(d-m.points[2].y)/d;if(r>i&&s>i&&o>i&&h>i&&m.result.moduleSize<Ke(this,os,"f").autoZoomInIdealModuleSize){if(Ke(this,os,"f").autoZoomInFrameArray.push(!0),Ke(this,os,"f").autoZoomInFrameArray.splice(0,Ke(this,os,"f").autoZoomInFrameArray.length-Ke(this,os,"f").autoZoomInFrameLimit[0]),Ke(this,os,"f").frameArrayInIdealZoom.length=0,Ke(this,ss,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{}),Ke(this,os,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=Ke(this,os,"f").autoZoomInFrameLimit[1]){Ke(this,os,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,Ke(this,os,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ke(this,os,"f").autoZoomInMaxTimes),Ke(this,os,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ke(this,os,"f").minValue,u),u=Math.min(Ke(this,os,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ke(this,os,"f").autoZoomInFrameArray.length=0,Ke(this,os,"f").frameArrayInIdealZoom.push(!0),Ke(this,os,"f").frameArrayInIdealZoom.splice(0,Ke(this,os,"f").frameArrayInIdealZoom.length-Ke(this,os,"f").frameLimitInIdealZoom[0]),Ke(this,os,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=Ke(this,os,"f").frameLimitInIdealZoom[1]&&(Ke(this,os,"f").frameArrayInIdealZoom.length=0,Ke(this,ss,"f").enhancedFocus)){const e=m.points;try{await a({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(!Ke(this,ss,"f").autoZoom&&Ke(this,ss,"f").enhancedFocus&&(Ke(this,os,"f").autoFocusFrameArray.push(!0),Ke(this,os,"f").autoFocusFrameArray.splice(0,Ke(this,os,"f").autoFocusFrameArray.length-Ke(this,os,"f").autoFocusFrameLimit[0]),Ke(this,os,"f").autoFocusFrameArray.filter(t=>!0===t).length>=Ke(this,os,"f").autoFocusFrameLimit[1])){Ke(this,os,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({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(Ke(this,ss,"f").autoZoom){if(Ke(this,os,"f").autoZoomInFrameArray.push(!1),Ke(this,os,"f").autoZoomInFrameArray.splice(0,Ke(this,os,"f").autoZoomInFrameArray.length-Ke(this,os,"f").autoZoomInFrameLimit[0]),Ke(this,os,"f").autoZoomOutFrameCount++,Ke(this,os,"f").frameArrayInIdealZoom.push(!1),Ke(this,os,"f").frameArrayInIdealZoom.splice(0,Ke(this,os,"f").frameArrayInIdealZoom.length-Ke(this,os,"f").frameLimitInIdealZoom[0]),Ke(this,os,"f").autoZoomOutFrameCount>=Ke(this,os,"f").autoZoomOutFrameLimit){Ke(this,os,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Ke(this,os,"f").autoZoomOutStepRate,Ke(this,os,"f").autoZoomOutMinStep);n=Math.max(Ke(this,os,"f").minValue,n),n=Math.min(Ke(this,os,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ke(this,ss,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!Ke(this,ss,"f").autoZoom&&Ke(this,ss,"f").enhancedFocus&&(Ke(this,os,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},Ze(this,as,new gs(1e4),"f")}setCameraView(t){if(!(t instanceof Or))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),Ke(this,Hr,"m",ls).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;Ke(this,Hr,"m",ls).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 Ke(this,Hr,"m",ls).call(this)?Ke(this,qr,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,Ke(this,Hr,"m",ls).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(Ke(this,Hr,"m",ls).call(this));else{try{await this.cameraManager.open(),Ze(this,Zr,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=ms.allowBeep?"":"none"),a&&(a.style.display=ms.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=ms.allowVibrate?"":"none"),l&&(l.style.display=ms.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const E=()=>{ms.allowBeep=!ms.allowBeep,o&&(o.style.display=ms.allowBeep?"":"none"),a&&(a.style.display=ms.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",E);const C=()=>{ms.allowVibrate=!ms.allowVibrate,h&&(h.style.display=ms.allowVibrate?"":"none"),l&&(l.style.display=ms.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",C);const S=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&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);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(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=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=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==qe?void 0:qe.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",E);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",C);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return Ze(this,qr,"open","f"),e&&(e._innerComponent.style.display="",Ke(this,Hr,"m",ls).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),Ke(this,Kr,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}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(),Ke(this,Hr,"m",ls).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())}Ze(this,qr,"closed","f"),Ke(this,as,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ke(this,Hr,"m",ls).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ke(this,Kr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ke(this,Hr,"m",ls).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.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})),this.toggleMirroring(this._isEnableMirroring),{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())?Ke(this,Kr,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ke(this,Kr,"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(Ke(this,Hr,"m",ls).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(Ke(this,Hr,"m",ls).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){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t<this._delay4AutoTorch))return;clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null}this._delay4AutoTorch=t;let n=!1,r=0,s=0;const o=async()=>{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(v.IPF_GRAYSCALED===o.format){for(let t=0;t<o.bytes.length;++t)a+=o.bytes[t];a/=o.bytes.length}else{if(v.IPF_ABGR_8888!==o.format)return;for(let t=0;t<o.bytes.length;t+=4)a+=o.bytes[t],a+=o.bytes[t+1],a+=o.bytes[t+2];a/=o.bytes.length/4*3}if(a<this.grayThreshold4AutoTorch){if(++r>=this.maxDarkCount4AutoTroch){null===(t=Es._onLog)||void 0===t||t.call(Es,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ke(this,Hr,"m",ls).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(Ke(this,Hr,"m",ls).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(Ke(this,Hr,"m",ls).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(Ke(this,Hr,"m",ls).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(Ke(this,Hr,"m",ls).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(Ke(this,Hr,"m",ls).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){Ke(this,os,"f").minValue=t.min,Ke(this,os,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ke(this,os,"f").minValue,max:Ke(this,os,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=kt.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!==jt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ai.EF_ENHANCED_FOCUS&&(Ke(this,ss,"f").enhancedFocus=!0),t&ai.EF_AUTO_ZOOM&&(Ke(this,ss,"f").autoZoom=!0),t&ai.EF_TAP_TO_FOCUS&&(Ke(this,ss,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ai.EF_ENHANCED_FOCUS&&(Ke(this,ss,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&ai.EF_AUTO_ZOOM&&(Ke(this,ss,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&ai.EF_TAP_TO_FOCUS&&(Ke(this,ss,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ke(this,Hr,"m",us).call(this)&&Ke(this,Hr,"m",cs).call(this)||Ke(this,as,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!R(t)&&!P(t))throw TypeError("Invalid 'region'.");Ze(this,es,t?JSON.parse(JSON.stringify(t)):null,"f"),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(Ke(this,es,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ze(this,ts,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ke(this,Hr,"m",ls).call(this))}startFetching(){if(Ke(this,Hr,"m",ls).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ke(this,ns,"f")||(Ze(this,ns,!0,"f"),Ke(this,Hr,"m",ds).call(this))}stopFetching(){Ke(this,ns,"f")&&(Es._onLog&&Es._onLog("DCE: stop fetching loop: "+Date.now()),Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),Ze(this,ns,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i;if(i=ji.convert(Ke(this,es,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y);const n=this.cameraView.regionMaskLineWidth;let r;r=Ke(this,es,"f")&&!t?{sx:i.x+n,sy:i.y+n,sWidth:i.width-2*n,sHeight:i.height-2*n,dWidth:i.width-2*n,dHeight:i.height-2*n}:{sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};const s=Math.max(r.dWidth,r.dHeight);if(this.canvasSizeLimit&&s>this.canvasSizeLimit){const t=this.canvasSizeLimit/s;r.dWidth>r.dHeight?(r.dWidth=this.canvasSizeLimit,r.dHeight=Math.round(r.dHeight*t)):(r.dWidth=Math.round(r.dWidth*t),r.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:r,pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?hi.GREY:hi.RGBA,isEnableMirroring:this._isEnableMirroring});if(!o)return null;let a;a=o.pixelFormat===hi.GREY?o.width:4*o.width;let h=!0;return 0===r.sx&&0===r.sy&&r.sWidth===e.width&&r.sHeight===e.height&&(h=!1),{bytes:o.data,width:o.width,height:o.height,stride:a,format:ps.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:ft.ITT_VIDEO_FRAME,isCropped:h,cropRegion:{left:r.sx,top:r.sy,right:r.sx+r.sWidth,bottom:r.sy+r.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:Ke(this,Qr,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ke(this,ns,"f")&&(Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),Ze(this,rs,setTimeout(()=>{this.disposed||Ke(this,Hr,"m",ds).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ze(this,is,t,"f")}getPixelFormat(){return Ke(this,is,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ke(this,Hr,"m",ls).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 o=ji.convert(Ke(this,es,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=Ke(this,$r,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ke(this,Hr,"m",fs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ke(this,Hr,"m",fs).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Ke(this,es,"f"))return JSON.parse(JSON.stringify(t));if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});Ze(this,Zr,t||Ke(this,Zr,"f"),"f")}let e,i,n=Ke(this,es,"f").left||Ke(this,es,"f").x||0,r=Ke(this,es,"f").top||Ke(this,es,"f").y||0;if(!Ke(this,es,"f").isMeasuredInPercentage)return{x:t.x-(n+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").x),y:t.y-(r+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").y)};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(!Ke(this,Hr,"m",ls).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ke(this,Hr,"m",ls).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Ke(this,Hr,"m",ls).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else e=Ke(this,Zr,"f").width,i=Ke(this,Zr,"f").height;return{x:t.x-(Math.round(n*e/100)+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").x),y:t.y-(Math.round(r*i/100)+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").y)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Ze(this,hs,!0,"f")}}var Cs,Ss,bs,Ts,Is,xs,Os,Rs;Xr=Es,qr=new WeakMap,Kr=new WeakMap,Zr=new WeakMap,Jr=new WeakMap,$r=new WeakMap,Qr=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,Hr=new WeakSet,ls=function(){return"disabled"!==this.singleFrameMode},cs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},us=function(){for(let t in Ke(this,ss,"f"))if(1==Ke(this,ss,"f")[t])return!0;return!1},ds=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ke(this,ns,"f"))return Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),void Ze(this,rs,setTimeout(()=>{this.disposed||Ke(this,Hr,"m",t).call(this)},this.fetchInterval),"f");const e=()=>{var t;let e;Es._onLog&&Es._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=Ke(this,ts,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=Ke(this,ts,"f"))||void 0===t||t.onErrorReceived(ct.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),Es._onLog&&Es._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ke(this,Kr,"f").fire("frameAddedToBuffer",null,{async:!1})):Es._onLog&&Es._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:e()}else e();Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),Ze(this,rs,setTimeout(()=>{this.disposed||Ke(this,Hr,"m",t).call(this)},this.fetchInterval),"f")},fs=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(!Ke(this,Hr,"m",ls).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ke(this,Hr,"m",ls).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:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ke(this,Hr,"m",ls).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u<d?(_=o/h,f=i+t.x*_,g=n+t.y*_+(a-l*_)/2,m=r+t.x*_,p=s+t.y*_+(a-l*_)/2):(_=a/l,f=i+t.x*_+(o-h*_)/2,g=n+t.y*_,m=r+t.x*_+(o-h*_)/2,p=s+t.y*_);else if("cover"===c)if(u<d){_=a/l;let e=t.x*_-(h*_-o)/2;e=Math.max(e,0),e=Math.min(e,o),f=i+e,g=n+t.y*_,m=r+e,p=s+t.y*_}else{_=o/h;let e=t.y*_-(l*_-a)/2;e=Math.max(e,0),e=Math.min(e,a),f=i+t.x*_,g=n+e,m=r+t.x*_,p=s+e}return{clientX:f,clientY:g,pageX:m,pageY:p}},Es._debug=!1,Es._isRTU=!1,zr={value:void 0},Es.browserInfo=qe;class As{get magnifierCanvas(){return Ke(this,Cs,"f")}constructor(){Cs.set(this,void 0),Ze(this,Cs,document.createElement("canvas"),"f"),Ke(this,Cs,"f").style.borderRadius="50%"}update(t,e,i,n){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");const r=this.magnifierCanvas;r.width=r.height=t;let s=e.x-i/2,o=e.y-i/2,a=i,h=i,l=r.width,c=r.height,u=r.getContext("2d");for(let t of n)u.drawImage(t.image,s,o,a,h,0,0,l,c);r.style.width=r.width+"px",r.style.height=r.height+"px"}show(){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");this.magnifierCanvas.style.display="block"}hide(){if(!this.magnifierCanvas)throw new Error("'magnifierCanvas' not created.");this.magnifierCanvas.style.display="none"}}Cs=new WeakMap;class Ds extends Ir{static async createInstance(t){const e=new Ds;return await e.setUIElement(t||Ke(e,Ss,"m",Rs).call(e)),e}get disposed(){return Ke(this,Os,"f")}constructor(){super(),Ss.add(this),this.containerClassName="dce-image-container",bs.set(this,void 0),Ts.set(this,void 0),this.isUseMagnifier=!0,Is.set(this,t=>{var e;if(!this.isUseMagnifier)return;if(Ke(this,Ts,"f")||Ze(this,Ts,new As,"f"),!Ke(this,Ts,"f").magnifierCanvas)return;document.body.contains(Ke(this,Ts,"f").magnifierCanvas)||(Ke(this,Ts,"f").magnifierCanvas.style.position="fixed",Ke(this,Ts,"f").magnifierCanvas.style.boxSizing="content-box",Ke(this,Ts,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ke(this,Ts,"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 Ke(this,xs,"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,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Ke(this,Ts,"f").update(s,t.pointer,r,o);{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?(Ke(this,Ts,"f").magnifierCanvas.style.left="auto",Ke(this,Ts,"f").magnifierCanvas.style.top="0",Ke(this,Ts,"f").magnifierCanvas.style.right="0"):(Ke(this,Ts,"f").magnifierCanvas.style.left="0",Ke(this,Ts,"f").magnifierCanvas.style.top="0",Ke(this,Ts,"f").magnifierCanvas.style.right="auto")}Ke(this,Ts,"f").show()}),xs.set(this,()=>{Ke(this,Ts,"f")&&Ke(this,Ts,"f").hide()}),Os.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Xi(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(O(t)){Ze(this,bs,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===v.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t<s.length;t+=4)s[t]=n[t/4],s[t+1]=n[t/4],s[t+2]=n[t/4],s[t+3]=255}else s=new Uint8ClampedArray(n.buffer);this.setImage(s,e,i)}else if(t instanceof HTMLCanvasElement)Ze(this,bs,t,"f"),this.setImage(t,t.width,t.height);else{if(!(t instanceof HTMLImageElement))throw new TypeError("Invalid img.");Ze(this,bs,t,"f"),this.setImage(t,t.naturalWidth,t.naturalHeight)}let e;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(e)}getOriginalImage(){return Ke(this,bs,"f")}getContentDimensions(){let t,e,i;if(this._innerComponent){const n=this._innerComponent.getElement("content");t=null==n?void 0:n.width,e=null==n?void 0:n.height,i="contain"}if(!t||!e)throw new Error("Invalid content dimensions.");return{width:t,height:e,objectFit:i}}_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)||300),i||(i=(null==r?void 0:r.height)||150),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);this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),t!=Sr.TIP_LAYER_ID&&s.setMode("editor");const o=this._drawingLayerManager._getFabricCanvas();return o&&(o.on("object:scaling",Ke(this,Is,"f")),o.on("object:rotating",Ke(this,Is,"f")),o.on("object:skewing",Ke(this,Is,"f")),o.on("mouse:up",Ke(this,xs,"f"))),s}dispose(){this._unbindUI(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}bs=new WeakMap,Ts=new WeakMap,Is=new WeakMap,xs=new WeakMap,Os=new WeakMap,Ss=new WeakSet,Rs=function(){const t=document.createElement("div");return t.className=this.containerClassName,t.style.width="100%",t.style.height="100%",t};var Ls=Object.freeze({__proto__:null,CameraEnhancer:Es,CameraEnhancerModule:class{static getVersion(){return"4.2.3-dev-20250812165927"}},CameraManager:Dr,CameraView:Or,DrawingItem:Si,DrawingStyleManager:Cr,get EnumDrawingItemMediaType(){return si},get EnumDrawingItemState(){return oi},get EnumEnhancedFeatures(){return ai},Feedback:ms,GroupDrawingItem:Pi,ImageDataGetter:Rr,ImageDrawingItem:class extends Si{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Ke(this,Ei,"f")}constructor(t,e,i,n){if(super(null,n),wi.set(this,void 0),Ei.set(this,void 0),!P(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new li.Image(t,{left:e.x,top:e.y}));else{if(!O(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===v.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e<n.length;e+=4)n[e]=t.bytes[e/4],n[e+1]=t.bytes[e/4],n[e+2]=t.bytes[e/4],n[e+3]=255}else n=new Uint8ClampedArray(t.bytes.buffer);i.getContext("2d").putImageData(new ImageData(n,t.width,t.height),0,0),this._setFabricObject(new li.Image(i,{left:e.x,top:e.y}))}}if(i){const t=e.width/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",e.width/this.get("width")),this.set("scaleY",e.height/this.get("height"));this.image=t,Ze(this,wi,JSON.parse(JSON.stringify(e)),"f"),Ze(this,Ei,i,"f"),this._mediaType="image"}extendSet(t,e){if("image"===t){if(e instanceof HTMLImageElement)return this._fabricObject.setElement(e),this.image=e,!0;if(e instanceof HTMLCanvasElement){const t=new Image;return t.src=e.toDataURL(),this._fabricObject.setElement(t),this.image=e,!0}throw new Error("Unsupported value.")}}extendGet(t){if("image"===t)return this.image}updateCoordinateBaseFromImageToView(){if(this.set("left",this.convertPropFromViewToImage(this.get("left"))),this.set("top",this.convertPropFromViewToImage(this.get("top"))),Ke(this,Ei,"f")){const t=this.convertPropFromViewToImage(this.get("width"))/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",this.convertPropFromViewToImage(this.get("width"))/this.get("width")),this.set("scaleY",this.convertPropFromViewToImage(this.get("height"))/this.get("height"))}updateCoordinateBaseFromViewToImage(){if(this.set("left",this.convertPropFromImageToView(this.get("left"))),this.set("top",this.convertPropFromImageToView(this.get("top"))),Ke(this,Ei,"f")){const t=this.convertPropFromImageToView(this.get("width"))/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",this.convertPropFromImageToView(this.get("width"))/this.get("width")),this.set("scaleY",this.convertPropFromImageToView(this.get("height"))/this.get("height"))}setPosition(t){this.setImageRect(t)}getPosition(){return this.getImageRect()}updatePosition(){Ke(this,wi,"f")&&this.setImageRect(Ke(this,wi,"f"))}setImage(t){const e=this.getImageRect();if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this.set("image",t);else{if(!O(t))throw new TypeError("Invalid 'image'.");{const e=document.createElement("canvas");let i;if(e.width=t.width,e.height=t.height,t.format===v.IPF_GRAYSCALED){i=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e<i.length;e+=4)i[e]=t.bytes[e/4],i[e+1]=t.bytes[e/4],i[e+2]=t.bytes[e/4],i[e+3]=255}else i=new Uint8ClampedArray(t.bytes.buffer);e.getContext("2d").putImageData(new ImageData(i,t.width,t.height),0,0),this.set("image",e)}}if(Ke(this,Ei,"f")){const t=e.width/this.get("width");this.set("scaleX",t),this.set("scaleY",t)}else this.set("scaleX",e.width/this.get("width")),this.set("scaleY",e.height/this.get("height"))}getImage(){return this.image}setImageRect(t){if(!P(t))throw new TypeError("Invalid 'rect'.");if(this._drawingLayer){if("view"===this.coordinateBase)if(this.set("left",this.convertPropFromViewToImage(t.x)),this.set("top",this.convertPropFromViewToImage(t.y)),Ke(this,Ei,"f")){const e=this.convertPropFromViewToImage(t.width)/this.get("width");this.set("scaleX",e),this.set("scaleY",e)}else this.set("scaleX",this.convertPropFromViewToImage(t.width)/this.get("width")),this.set("scaleY",this.convertPropFromViewToImage(t.height)/this.get("height"));else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");if(this.set("left",t.x),this.set("top",t.y),Ke(this,Ei,"f")){const e=t.width/this.get("width");this.set("scaleX",e),this.set("scaleY",e)}else this.set("scaleX",t.width/this.get("width")),this.set("scaleY",t.height/this.get("height"))}this._drawingLayer.renderAll()}else Ze(this,wi,JSON.parse(JSON.stringify(t)),"f")}getImageRect(){if(this._drawingLayer){if("view"===this.coordinateBase)return{x:this.convertPropFromImageToView(this.get("left")),y:this.convertPropFromImageToView(this.get("top")),width:this.convertPropFromImageToView(this.get("scaledWidth")),height:this.convertPropFromImageToView(this.get("scaledHeight"))};if("image"===this.coordinateBase)return{x:this.get("left"),y:this.get("top"),width:this.get("scaledWidth"),height:this.get("scaledHeight")};throw new Error("Invalid 'coordinateBase'.")}return Ke(this,wi,"f")?JSON.parse(JSON.stringify(Ke(this,wi,"f"))):null}},ImageEditorView:Ds,LineDrawingItem:class extends Ri{constructor(t,e){if(super({points:[null==t?void 0:t.startPoint,null==t?void 0:t.endPoint]},e),Li.set(this,void 0),!D(t))throw new TypeError("Invalid 'line'.");Ze(this,Li,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="line"}extendSet(t,e){if("startPoint"===t||"endPoint"===t){e="startPoint"===t?[e,this.get("endPoint")]:[this.get("startPoint"),e];const i=this._fabricObject;if(i.group){const t=i.group;i.points=e.map(e=>({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 li.Control({positionHandler:Ti,actionHandler:Oi(i>0?i-1:n,xi),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=li.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(){Ke(this,Li,"f")&&this.setLine(Ke(this,Li,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!D(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 Ze(this,Li,JSON.parse(JSON.stringify(t)),"f")}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 Ke(this,Li,"f")?JSON.parse(JSON.stringify(Ke(this,Li,"f"))):null}},QuadDrawingItem:Fi,RectDrawingItem:bi,TextDrawingItem:Di});const Ms="undefined"==typeof self,Fs=Ms?{}:self,Ps="function"==typeof importScripts,ks=(()=>{if(!Ps){if(!Ms&&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"./"}})(),Ns=t=>t&&"object"==typeof t&&"function"==typeof t.then,Bs=(async()=>{})().constructor;let js=class extends Bs{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,Ns(t)?e=t:"function"==typeof t&&(e=new Bs(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&&(Ns(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Us=" is not allowed to change after `createInstance` or `loadWasm` is called.",Vs=!Ms&&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"))||"",Gs=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Us);i._license=e}};!Ms&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ws=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e<t.length;++e){if(!Ms){let i=document.createElement("a");i.href=t[e],t[e]=i.href}t[e].endsWith("/")||(t[e]+="/")}}return t},Ys=(t,e)=>{e=Ws(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Us);i._licenseServer=e}},Hs=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Us);i._deviceFriendlyName=e}};let Xs,zs,qs,Ks,Zs;"undefined"!=typeof navigator&&(Xs=navigator,zs=Xs.userAgent,qs=Xs.platform,Ks=Xs.mediaDevices),function(){if(!Ms){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Xs.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:qs,search:"Win"},Mac:{str:qs},Linux:{str:qs}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||zs,o=r.search||e,a=r.verStr||zs,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||zs,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=zs.indexOf("Windows NT")&&(r="HarmonyOS"),Zs={browser:i,version:n,OS:r}}Ms&&(Zs={browser:"ssr",version:0,OS:"ssr"})}(),Ks&&Ks.getUserMedia,"Chrome"===Zs.browser&&Zs.version>66||"Safari"===Zs.browser&&Zs.version>13||"OPR"===Zs.browser&&Zs.version>43||"Edge"===Zs.browser&&Zs.version;const Js=()=>(jt.loadWasm(),It("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,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.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(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Ws(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Fs.crypto||(s="Please upgrade your browser to support online key."),Fs.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Us)})(Qs),o=new js;Qs._pLoad.task=o,(async()=>{try{await Qs._pLoad}catch(t){}})();let a=Rt();At[a]=e=>{if(e.message&&Qs._onAuthMessage){let t=Qs._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(Dt&&Dt("init license success"),e.message&&console.warn(e.message),jt._bSupportIRTModule=e.bSupportIRTModule,jt._bSupportDce4Module=e.bSupportDce4Module,Qs.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.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=B(jt.engineResourcePaths),i=("DCV"===jt._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(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.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t<s.childElementCount;++t){let e=s.children[t];e instanceof HTMLStyleElement&&(o.push(e),document.head.append(e))}let a=1==s.childElementCount?s.children[0]:s;a.remove();let h,l,c,u,d,f=[a],g=a.children;for(let t of g)f.push(t);for(let t=0;t<f.length;++t)for(let e of f[t].children)f.push(e);for(let t of f)if(!h&&t.classList.contains("dls-license-mask"))h=t,t.addEventListener("click",e=>{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)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 o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Qs._bNeverShowDialog,engineResourcePath:i,_onLog:Dt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await Tt("core"),xt.postMessage({type:"license_dynamsoft",body:{v:"4.0.60-dev-20250812170103",brtk:!!t,bptk:1===t,l:e,os:Zs,fn:Qs.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),Qs.bCallInitLicense=!0,await o}));let $s;kt.license={},kt.license.dynamsoft=Js,kt.license.getAR=async()=>{{let t=bt.dynamsoft_inited;t&&t.isRejected&&await t}return xt?new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){delete i.success;{let t=Qs.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)}},xt.postMessage({type:"license_getAR",id:i})}):null};let Qs=class t{static setLicenseServer(e){Ys(t,e)}static get license(){return this._license}static set license(e){Gs(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Ys(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Hs(t,e)}static initLicense(e,i){if(Gs(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Js()}static setDeviceFriendlyName(e){Hs(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await It("dynamsoft_uuid",async()=>{await jt.loadWasm();let t=new js,e=Rt();At[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},xt.postMessage({type:"license_getDeviceUUID",id:e}),$s=await t}),$s))()}};Qs._pLoad=new js,Qs.bPassValidation=!1,Qs.bCallInitLicense=!1,Qs._license=Vs,Qs._licenseServer=[],Qs._deviceFriendlyName="",jt.engineResourcePaths.license={version:"4.0.60-dev-20250812170103",path:ks,isInternal:!0},Nt.license={wasm:!0,js:!0},kt.license.LicenseManager=Qs;const to="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,to)<0&&(jt.engineResourcePaths.std={version:to,path:(t=>{if(null==t&&(t="./"),Ms||Ps);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(ks+`../../dynamsoft-capture-vision-std@${to}/dist/`),isInternal:!0});var eo=Object.freeze({__proto__:null,LicenseManager:Qs,LicenseModule:class{static getVersion(){return`4.0.60-dev-20250812170103(Worker: ${Pt.license&&Pt.license.worker||"Not Loaded"}, Wasm: ${Pt.license&&Pt.license.wasm||"Not Loaded"})`}}});const io=()=>window.matchMedia("(orientation: landscape)").matches,no=t=>Object.prototype.toString.call(t).slice(8,-1);function ro(t,e){for(const i in e)"Object"===no(e[i])&&i in t?ro(t[i],e[i]):t[i]=e[i];return t}function so(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function oo(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;i<t.length;i++)e[i]=oo(t[i])}else{e={};for(let i in t)t.hasOwnProperty(i)&&(e[i]=oo(t[i]))}return e}function ao(t){if(!t)return!1;const e=t.name.toLowerCase();if(![".jpg",".jpeg",".ico",".gif",".svg",".webp",".png",".bmp"].some(t=>e.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const ho="undefined"==typeof self,lo="function"==typeof importScripts,co=(()=>{if(!lo){if(!ho&&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"./"}})(),uo=t=>{if(null==t&&(t="./"),ho||lo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};jt.engineResourcePaths.utility={version:"2.0.60-dev-20250812170132",path:co,isInternal:!0},Nt.utility={js:!0,wasm:!0};const fo="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,fo)<0&&(jt.engineResourcePaths.std={version:fo,path:uo(co+`../../dynamsoft-capture-vision-std@${fo}/dist/`),isInternal:!0});const go="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,go)<0)&&(jt.engineResourcePaths.dip={version:go,path:uo(co+`../../dynamsoft-image-processing@${go}/dist/`),isInternal:!0});function mo(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"==typeof SuppressedError&&SuppressedError;const po="undefined"==typeof self,_o="function"==typeof importScripts,vo=(()=>{if(!_o){if(!po&&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"./"}})(),yo=t=>{if(null==t&&(t="./"),po||_o);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};jt.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:vo,isInternal:!0},Nt.dbr={js:!1,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},kt.dbr={};const wo="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,wo)<0&&(jt.engineResourcePaths.std={version:wo,path:yo(vo+`../../dynamsoft-capture-vision-std@${wo}/dist/`),isInternal:!0});const Eo="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,Eo)<0)&&(jt.engineResourcePaths.dip={version:Eo,path:yo(vo+`../../dynamsoft-image-processing@${Eo}/dist/`),isInternal:!0});const Co={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),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_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var So,bo,To,Io,xo,Oo,Ro,Ao,Do,Lo;function Mo(t,e){let i=!0;for(let o=0;o<t.length;o++){const a=(o+1)%t.length;if(n=t[o],s=e,((r=t[a]).x-n.x)*(s.y-n.y)-(r.y-n.y)*(s.x-n.x)<0){i=!1;break}}var n,r,s;return i}function Fo(t,e){return Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2)}function Po(t,e){const[i,n]=t,r=i.x,s=i.y,o=n.x,a=n.y,h=e.x,l=e.y,c=(o-r)**2+(a-s)**2;if(0===c)return Math.sqrt((h-r)**2+(l-s)**2);const u=((h-r)*(o-r)+(l-s)*(a-s))/c;if(u<0)return Math.sqrt((h-r)**2+(l-s)**2);if(u>1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function ko(t){const e=[];for(let i=0;i<t.length;i++){const n=t[i],r=t[(i+1)%t.length];e.push([n,r])}return e}function No(t){const[e,i]=t;return{x:(e.x+i.x)/2,y:(e.y+i.y)/2}}function Bo(t,e,i,n){const r=e.x-t.x,s=e.y-t.y,o=n.x-i.x,a=n.y-i.y,h=(-s*(t.x-i.x)+r*(t.y-i.y))/(-o*s+r*a),l=(o*(t.y-i.y)-a*(t.x-i.x))/(-o*s+r*a);return h>=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function jo(t){let e=0;for(let i=0;i<t.length;i++){const n=(i+1)%t.length;e+=t[i].x*t[n].y,e-=t[n].x*t[i].y}return Math.abs(e/2)}function Uo(t,e,i){let n=e.x-t.x,r=e.y-t.y,s=i.x-t.x;return n*(i.y-t.y)-r*s>0}function Vo(t,e){for(let i=0;i<4;i++)if(!Uo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}(xo=So||(So={}))[xo.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",xo[xo.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",xo[xo.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(bo||(bo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(To||(To={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(Io||(Io={}));function Go(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=ko(r)[3],h=ko(r)[1],l=ko(s)[3],c=ko(s)[1];let u,d=0;if(u=Math.max(Math.abs(Po(a,e.points[0])),Math.abs(Po(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(h,e.points[1])),Math.abs(Po(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Po(l,t.points[0])),Math.abs(Po(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(c,t.points[1])),Math.abs(Po(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=No(ko(r)[0]),g=No(ko(r)[2]),m=No(ko(s)[0]),p=No(ko(s)[2]),_=Fo(f,p),v=Fo(m,g),y=_>v,w=Math.min(_,v),E=Fo(f,g),C=Fo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,E),S=Math.min(S,C),!!(w<S||Mo(r,y?m:p)||Mo(s,y?g:f))&&(y?(n.points[0]=t.points[0],n.points[1]=t.points[1],n.points[2]=e.points[2],n.points[3]=e.points[3]):(n.points[0]=e.points[0],n.points[1]=e.points[1],n.points[2]=t.points[2],n.points[3]=t.points[3]),n.area=jo(n.points),!0)}class Wo{constructor(t,e,i,n){this.overlapCount=t,this.verificationCount=e,this.crossVerificationFrame=5,this.location=n.location,this.locationArea=n.location.area,this.locationAngle=n.angle,this.format=n.format,this.text=n.text,this.isOneD=i,this.item=n,this.locationThreshold=5*n.moduleSize,this.strictLimit=Math.max(this.locationThreshold,1),this.strictLimit=Math.min(this.strictLimit,15)}getCenterPoint(t){const e={x:0,y:0};return t.forEach(({x:t,y:i})=>{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),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Vo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Vo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Vo(t,this.location.points[e]))return!0;if(Vo(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(Po(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;if(Math.abs(r.y+e.y-n.y)>=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=Bo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{Mo(e,t)&&i.push(t)}),e.forEach(e=>{Mo(t,e)&&i.push(e)}),jo(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 Yo={barcode:2,text_line:4,detected_quad:8,deskewed_image:16},Ho=t=>Object.values(Yo).includes(t)||Yo.hasOwnProperty(t),Xo=(t,e)=>"string"==typeof t?e[Yo[t]]:e[t],zo=(t,e,i)=>{"string"==typeof t?e[Yo[t]]=i:e[t]=i},qo=(t,e,i)=>{const n=[{type:ht.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:ht.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class Ko{constructor(){this.verificationEnabled={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!0,[ht.CRIT_DETECTED_QUAD]:!0,[ht.CRIT_DESKEWED_IMAGE]:!1},this.duplicateFilterEnabled={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1},this.duplicateForgetTime={[ht.CRIT_BARCODE]:3e3,[ht.CRIT_TEXT_LINE]:3e3,[ht.CRIT_DETECTED_QUAD]:3e3,[ht.CRIT_DESKEWED_IMAGE]:3e3},this.latestOverlappingEnabled={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[ht.CRIT_BARCODE]:5,[ht.CRIT_TEXT_LINE]:5,[ht.CRIT_DETECTED_QUAD]:5,[ht.CRIT_DESKEWED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,Oo.set(this,new Map),Ro.set(this,new Map),Ao.set(this,new Map),Do.set(this,new Map),Lo.set(this,new Map),Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),qo(this,t,ht.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{qo(this,t,ht.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){mo(this,Oo,"f").forEach((t,e)=>{zo(e,this.verificationEnabled,t)}),mo(this,Ro,"f").forEach((t,e)=>{zo(e,this.duplicateFilterEnabled,t)}),mo(this,Ao,"f").forEach((t,e)=>{zo(e,this.duplicateForgetTime,t)}),mo(this,Do,"f").forEach((t,e)=>{zo(e,this.latestOverlappingEnabled,t)}),mo(this,Lo,"f").forEach((t,e)=>{zo(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){Ho(t)&&mo(this,Oo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Ho(t)&&Xo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Ho(t)&&(e&&this.enableLatestOverlapping(t,!1),mo(this,Ro,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Ho(t)&&Xo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Ho(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),mo(this,Ao,"f").set(t,e))}getDuplicateForgetTime(t){return Ho(t)?Xo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Ho(t)&&mo(this,Lo,"f").set(t,e)}getMaxOverlappingFrames(t){return Ho(t)?Xo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Ho(t)&&(e&&this.enableResultDeduplication(t,!1),mo(this,Do,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Ho(t)&&Xo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[ht.CRIT_BARCODE,ht.CRIT_TEXT_LINE,ht.CRIT_DETECTED_QUAD,ht.CRIT_DESKEWED_IMAGE];for(let i=0;i<e.length;i++)(this.verificationEnabled[e[i]]||this.duplicateFilterEnabled[e[i]])&&(t|=e[i]);return t}latestOverlappingFilter(t){var e,i,n;const r=this.isResultCrossVerificationEnabled(ht.CRIT_BARCODE),s=this.isLatestOverlappingEnabled(ht.CRIT_BARCODE);if(s){const o=5,a=60,h=s?this.getMaxOverlappingFrames(ht.CRIT_BARCODE):5,l=t.items.length,c=null===(n=null===(i=null===(e=null==t?void 0:t.intermediateResult)||void 0===e?void 0:e[0])||void 0===i?void 0:i.intermediateResultUnits)||void 0===n?void 0:n[1].localizedBarcodes,u=c?c.length:0;let d=[];const f=[],g={x:0,y:0};let m=new Array(l).fill(-1),p=0;const _=t.items.map(t=>{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0);return new Wo(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e<l;){const i={x:0,y:0},n=new Array(l).fill(-1);let r=!1;for(;e<l;e++){if(!_[e])continue;const s=_[e].item;for(let o=0;o<this.overlapSet.length;o++){if(t[e][o]<1)continue;const a=this.overlapSet[o],h=a.item;if(s.format===h.format&&s.text===h.text){if(r=a.isProbablySameLocationWithOffset(_[e],i),r){n[e]=o,t[e][o]=0;break}}else t[e][o]=0}if(r)break}if(r){for(let r=0;r<l;r++){if(r===e||!_[r])continue;const s=_[r].item;for(let e=0;e<this.overlapSet.length;e++){if(t[r][e]<1)continue;if(n.includes(e))continue;const o=this.overlapSet[e],a=o.item;if(s.format===a.format&&s.text===a.text){if(o.isMatchedLocationWithOffset(_[r],i)){n[r]=e,t[r][e]=0;break}}else t[r][e]=0}}const r=n.filter(t=>-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<l;e++){const i=_[e].item;for(let n=0;n<this.overlapSet.length;n++){if(t[e][n]<1)continue;if(m.includes(n))continue;const r=this.overlapSet[n],s=r.item;if(i.format===s.format&&i.text===s.text){if(r.isMatchedLocationWithOffset(_[e])){m[e]=n,t[e][n]=0;break}}else t[e][n]=0}}p+=m.filter(t=>-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<this.overlapSet.length;e++){const i=this.overlapSet[e];for(let e=0;e<u;e++)if(i.isOverlappedLocationWithOffset(c[e],g)){t++;break}}i=this.overlapSet.length<=3?t>=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(Co.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence<a,o=new Wo(h,n?1:2,n,i);r&&n&&s&&f.push(e),this.overlapSet.push(o)}});else{let e=!0;s?(Math.abs(g.x)>5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i<t.items.length;i++){const t=m[i];if(t<0&&_[i]){const t=_[i].item;let n={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};for(let i=0;i<4;i++)n.points[i].x=e?t.location.points[i].x-g.x:t.location.points[i].x,n.points[i].y=e?t.location.points[i].y-g.y:t.location.points[i].y;for(let r=0;r<this.overlapSet.length;r++){if(m.includes(r))continue;const s=this.overlapSet[r].item.text,o=this.overlapSet[r].item.format;if(t.format===o&&t.text===s){if(this.overlapSet[r].isOverlappedLocationWithOffset(t,g,!1)){const e=Object.assign({},t),n=(BigInt(e.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0),s=n?1:2;this.overlapSet[r]=new Wo(h,s,n,e),m[i]=r;break}if(_[i].isOneD){let s={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};for(let t=0;t<4;t++)s.points[t].x=e?this.overlapSet[r].location.points[t].x:this.overlapSet[r].location.points[t].x+g.x,s.points[t].y=e?this.overlapSet[r].location.points[t].y:this.overlapSet[r].location.points[t].y+g.y;let o={points:[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}],area:0};if(Go(n,s,t.moduleSize,o)){t.location=o;const e=Object.assign({},t),n=(BigInt(e.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0),s=n?1:2;this.overlapSet[r]=new Wo(h,s,n,e),m[i]=r;break}}}}}else{if(e)_[i]&&(_[i].item.location=this.overlapSet[t].location);else{const e=Object.assign({},_[i].item),n=(BigInt(e.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(e.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0),r=n?1:2;this.overlapSet[t]=new Wo(h,r,n,e)}this.overlapSet[t]&&(this.overlapSet[t].overlapCount=h,this.overlapSet[t].verificationCount=2,this.overlapSet[t].crossVerificationFrame=o)}}e?this.stabilityCount<15&&this.stabilityCount++:this.stabilityCount=0;let i=!0;for(let t=0;t<this.overlapSet.length;t++){if(m.includes(t))continue;const n=this.overlapSet[t];n.overlapCount--,n.crossVerificationFrame--;const r=n.overlapCount+this.stabilityCount;if(s&&r>0){for(let t=0;t<l;t++)if(n.isOverlappedLocationWithOffset(_[t],g,!1)){i=!1;break}if(!i)break;const t=n.item;if(!e){for(let t=0;t<4;t++)n.location.points[t].x+=g.x,n.location.points[t].y+=g.y;t.location=n.location}2===n.verificationCount&&d.push(t)}}if(s&&!i){d=[];for(let t=0;t<this.overlapSet.length;t++){if(m.includes(t))continue;const e=this.overlapSet[t];e.overlapCount=0-this.stabilityCount,e.crossVerificationFrame=0,e.verificationCount=0}}for(let t=0;t<l;t++){if(-1!==m[t]||!_[t])continue;const i=_[t].item;if(e){for(let e=0;e<4;e++)_[t].location.points[e].x-=g.x,_[t].location.points[e].y-=g.y;i.location=_[t].location}let n=!1;for(let e of this.overlapSet)if(!(e.crossVerificationFrame<=0&&e.verificationCount<=0)&&(n=e.isLocationOverlap(_[t].location,_[t].locationArea),n))break;if(n){f.push(t);continue}const s=Object.assign({},i),o=(BigInt(i.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(i.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0),l=i.confidence<a,c=new Wo(h,o?1:2,o,s);r&&o&&l?f.push(t):c.verificationCount=2,this.overlapSet.push(c)}this.overlapSet=this.overlapSet.filter(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}))})}}}Oo=new WeakMap,Ro=new WeakMap,Ao=new WeakMap,Do=new WeakMap,Lo=new WeakMap;const Zo=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:v.IPF_ABGR_8888}};var Jo,$o,Qo,ta;class ea{async readFromFile(t){return await Zo(t)}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=G(t);return j(n,e,i)}async readFromMemory(t){if(!mo(ea,Jo,"f",$o).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=mo(ea,Jo,"f",$o).get(t);return await new Promise((t,n)=>{let r=Rt();At[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},xt.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{var i,n;if(e.success)return function(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");r?r.value=i:e.set(t,i)}(i=ea,Jo,(n=mo(i,Jo,"f",Qo),++n),0,Qo),mo(ea,Jo,"f",$o).set(mo(ea,Jo,"f",Qo),JSON.parse(e.memery)),t(mo(ea,Jo,"f",Qo));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}Jo=ea,$o={value:new Map},Qo={value:0};!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(ta||(ta={}));var ia,na,ra,sa,oa,aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ea,Ca,Sa,ba,Ta,Ia,xa,Oa=Object.freeze({__proto__:null,get EnumFilterType(){return ta},ImageDrawer:class{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await Zo(t);else if("string"==typeof t){let e=await k(t,"blob");a=await Zo(e)}else O(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=Rt();At[l]=async e=>{if(e.success)return o&&(new ea).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},xt.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}},ImageIO:ea,ImageProcessor:class{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await Zo(t);return await new Promise((t,l)=>{let c=Rt();At[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},xt.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await Zo(t);return await new Promise((t,h)=>{let l=Rt();At[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},xt.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await Zo(t);return await new Promise((t,l)=>{let c=Rt();At[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},xt.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}},MultiFrameResultCrossFilter:Ko,UtilityModule:class{static getVersion(){return`2.0.60-dev-20250812170132(Worker: ${Pt.utility&&Pt.utility.worker||"Not Loaded"}, Wasm: ${Pt.utility&&Pt.utility.wasm||"Not Loaded"})`}}});class Ra{constructor(e){if(ia.add(this),sa.set(this,void 0),oa.set(this,{status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]}),aa.set(this,!1),ha.set(this,void 0),la.set(this,void 0),ca.set(this,void 0),ua.set(this,void 0),this.config=oo(Vt),e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";ro(this.config,e),Es._isRTU=!0}get disposed(){return i(this,aa,"f")}launch(){return e(this,void 0,void 0,function*(){if(i(this,aa,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(i(Ra,na,"f",ra)&&!i(Ra,na,"f",ra).isFulfilled&&!i(Ra,na,"f",ra).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return n(Ra,na,new Yt,"f",ra),yield i(this,ia,"m",da).call(this),i(Ra,na,"f",ra)})}decode(t,r="ReadBarcodes_Default"){return e(this,void 0,void 0,function*(){n(this,la,r,"f"),yield i(this,ia,"m",fa).call(this,!0),i(this,ua,"f")||n(this,ua,new Ko,"f"),i(this,ua,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(i(this,ua,"f"));const e=new Be;e.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(e);const s=yield this._cvRouter.capture(t,r);return i(this,ua,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(i(this,ua,"f")),this._cvRouter.removeResultReceiver(e),s})}dispose(){var t,e,r,s,o,a,h;n(this,aa,!0,"f"),i(Ra,na,"f",ra)&&i(Ra,na,"f",ra).isPending&&i(Ra,na,"f",ra).resolve(i(this,oa,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(e=this._cameraView)||void 0===e||e.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",i(this,sa,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}na=Ra,sa=new WeakMap,oa=new WeakMap,aa=new WeakMap,ha=new WeakMap,la=new WeakMap,ca=new WeakMap,ua=new WeakMap,ia=new WeakSet,da=function(){return e(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield i(this,ia,"m",fa).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),so(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){i(this,ia,"m",ba).call(this),i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(i(this,la,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(e){i(this,oa,"f").status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(Ra,na,"f",ra).reject(new Error(i(this,oa,"f").status.message)),this.dispose()}finally{i(this,ia,"m",Ia).call(this,"Loading...",!1)}})},fa=function(r=!1){return e(this,void 0,void 0,function*(){if(jt.engineResourcePaths=this.config.engineResourcePaths,!r){const e=B(jt.engineResourcePaths);if(this._cameraView=yield Or.createInstance(e.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),this._cameraEnhancer=yield Es.createInstance(this._cameraView),this.disposed)return;if(yield i(this,ia,"m",ma).call(this),this.disposed)return;if(this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1),n(this,ca,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}}yield Qs.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield Ne.createInstance()),this.disposed||(this.config.scanMode!==t.EnumScanMode.SM_SINGLE||r?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{i(Ra,na,"f",ra).reject(new Error(t.message)),this.dispose()},yield i(this,ia,"m",ga).call(this,r),this.disposed||r||(this._cvRouter.setInput(this._cameraEnhancer),i(this,ia,"m",pa).call(this),yield i(this,ia,"m",_a).call(this),this.disposed)))})},ga=function(r=!1){return e(this,void 0,void 0,function*(){if(r||(this.config.scanMode===t.EnumScanMode.SM_SINGLE?n(this,la,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&n(this,la,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const e=yield this._cvRouter.getSimplifiedSettings(i(this,la,"f"));if(this.disposed)return;r||this.config.scanMode!==t.EnumScanMode.SM_SINGLE||(e.outputOriginalImage=!0);let s=this.config.barcodeFormats;if(s){Array.isArray(s)||(s=[s]),e.barcodeSettings.barcodeFormatIds=BigInt(0);for(let t=0;t<s.length;t++){if("bigint"!=typeof s[t])throw new Error(`Invalid barcodeFormats [${s[t]}] Index ${t}.`);e.barcodeSettings.barcodeFormatIds|=s[t]}}yield this._cvRouter.updateSettings(i(this,la,"f"),e),this.disposed})},ma=function(){var r,s,o,h,l,c,u,d,f;return e(this,void 0,void 0,function*(){const g=this.config.uiPath,m=g.endsWith("/")?a(g)+"ui/barcode-scanner.ui.xml":a(g).slice(0,-1),p=yield(_=m,e(void 0,void 0,void 0,function*(){if("string"!=typeof _)throw new TypeError("Invalid url.");const t=yield fetch(_);if(!t.ok)throw Error("Network Error: "+t.statusText);const e=yield t.text();if(!e.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const i=document.createElement("div");if(i.insertAdjacentHTML("beforeend",e),1===i.childElementCount&&i.firstChild instanceof HTMLTemplateElement)return i.firstChild.content;const n=new DocumentFragment;for(let t of i.children)n.append(t);return n}));var _;if(this.disposed)return;p.querySelectorAll("style").forEach(t=>{document.head.appendChild(t.cloneNode(!0))}),n(this,ha,p.querySelector(".result-item"),"f");const y=p.querySelector(".btn-clear");if(y&&(y.addEventListener("click",()=>{i(this,oa,"f").barcodeResults=[],i(this,ia,"m",Ca).call(this)}),null===(o=null===(s=null===(r=this.config)||void 0===r?void 0:r.resultViewConfig)||void 0===s?void 0:s.toolbarButtonsConfig)||void 0===o?void 0:o.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;y.style.display=t.isHidden?"none":"flex",y.className=t.className?t.className:"btn-clear",y.innerText=t.label?t.label:"Clear",t.isHidden&&(p.querySelector(".toolbar-btns").style.justifyContent="center")}const w=p.querySelector(".btn-done");if(w&&(w.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(c=null===(l=null===(h=this.config)||void 0===h?void 0:h.resultViewConfig)||void 0===l?void 0:l.toolbarButtonsConfig)||void 0===c?void 0:c.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;w.style.display=t.isHidden?"none":"flex",w.className=t.className?t.className:"btn-done",w.innerText=t.label?t.label:"Done",t.isHidden&&(p.querySelector(".toolbar-btns").style.justifyContent="center")}if(null===(d=null===(u=this.config)||void 0===u?void 0:u.scannerViewConfig)||void 0===d?void 0:d.showCloseButton){const e=p.querySelector(".btn-close");e&&(e.style.display="",e.addEventListener("click",()=>{i(this,oa,"f").barcodeResults=[],i(this,oa,"f").status={code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}if(null===(f=this.config)||void 0===f?void 0:f.scannerViewConfig.showFlashButton){const t=p.querySelector(".btn-flash-auto"),n=p.querySelector(".btn-flash-open"),r=p.querySelector(".btn-flash-close");if(t){t.style.display="";let s=null,o=250,a=20,h=3;const l=(l=250)=>e(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==s){if(!(l<o))return;clearInterval(s),s=null}o=l;let u=!1,d=0,f=0;const g=()=>e(this,void 0,void 0,function*(){var e;if(i(this,aa,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(s),void(s=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(s),s=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(v.IPF_GRAYSCALED===l.format){for(let t=0;t<l.bytes.length;++t)c+=l.bytes[t];c/=l.bytes.length}else{if(v.IPF_ABGR_8888!==l.format)return;for(let t=0;t<l.bytes.length;t+=4)c+=l.bytes[t],c+=l.bytes[t+1],c+=l.bytes[t+2];c/=l.bytes.length/4*3}if(c<a){if(++d>=h){null===(e=Es._onLog)||void 0===e||e.call(Es,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,t.style.display="none",n.style.display="",r.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});s=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),t.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),t.style.display="none",n.style.display="",r.style.display="none"})),n.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),t.style.display="none",n.style.display="none",r.style.display=""})),r.addEventListener("click",()=>e(this,void 0,void 0,function*(){l(1e3),t.style.display="",n.style.display="none",r.style.display="none"}))}}let E=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(E)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const t=p.querySelector(".camera-control");if(t){t.style.display="";const n=yield this._cameraEnhancer.getAllCameras(),r=this.config.scannerViewConfig.cameraSwitchControl,s=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px"}),e},o=()=>{if(0===n.length)return null;if("listAll"===r){const t=p.querySelector(".camera-list");for(let e of n){const i=s(e);t.append(i)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const r=t=>{for(let e of o)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};t.addEventListener("click",t=>e(this,void 0,void 0,function*(){const e=t.target;i(this,ia,"m",Ia).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:e.deviceId,label:e.label,_checked:e._checked});const n=this._cameraEnhancer.getSelectedCamera(),s=this._cameraEnhancer.getCapabilities();so(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(s.torch?i(this,ia,"m",Ta).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),r(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(i(this,la,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),i(this,ia,"m",Ia).call(this,"Loading...",!1)}));const o=p.querySelectorAll(".camera-list div");return()=>e(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();r(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===r?()=>e(this,void 0,void 0,function*(){i(this,ia,"m",Ia).call(this,"Accessing Camera...",!0);const t=so(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&i(this,ia,"m",Ta).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),i(this,ia,"m",Ia).call(this,"Loading...",!1)}):void 0},a=o();t.addEventListener("click",t=>e(this,void 0,void 0,function*(){t.stopPropagation(),a&&(yield a())}))}}this.config.showUploadImageButton&&i(this,ia,"m",ba).call(this,p.querySelector(".btn-upload-image"));const C=this._cameraView.getUIElement();C.shadowRoot.querySelector(".dce-sel-camera").remove(),C.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const S=p.querySelector(".barcode-scanner-container");S.style.display=io()?"flex":"",this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this.config.showResultView=!1);const b=this.config.showResultView;let T;if(this.config.container?(S.style.position="relative",T=this.config.container):T=document.body,"string"==typeof T&&(T=document.querySelector(T),null===T))throw new Error("Failed to get the container");let I=this.config.scannerViewConfig.container;if("string"==typeof I&&(I=document.querySelector(I),null===I))throw new Error("Failed to get the container of the scanner view.");let x=this.config.resultViewConfig.container;if("string"==typeof x&&(x=document.querySelector(x),null===x))throw new Error("Failed to get the container of the result view.");const O=p.querySelector(".scanner-view-container"),R=p.querySelector(".result-view-container"),A=p.querySelector(".loading-page");O.append(A),I&&(O.append(C),I.append(O)),x&&x.append(R),I||x?I&&!x?(this.config.container||(R.style.position="absolute"),x=R,T.append(R)):!I&&x&&(this.config.container||(O.style.position="absolute"),I=O,O.append(C),T.append(O)):(I=O,x=R,b&&(Object.assign(O.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"}),Object.assign(R.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"})),O.append(C),T.append(S)),document.querySelector(".result-view-container").style.display=b?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),n(this,sa,()=>{Object.assign(S.style,{display:io()?"flex":""}),!b||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(I.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"}),Object.assign(x.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"}))},"f"),window.addEventListener("resize",i(this,sa,"f")),this._cameraView._createDrawingLayer(2)})},pa=function(){const n=new Be;n.onCapturedResultReceived=n=>e(this,void 0,void 0,function*(){if(i(this,ca,"f")&&i(this,ca,"f").clearDrawingItems(),n.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of n.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));i(this,ca,"f").addDrawingItems(t)}this.config.scanMode===t.EnumScanMode.SM_SINGLE?i(this,ia,"m",va).call(this,n):i(this,ia,"m",ya).call(this,n)}}),this._cvRouter.addResultReceiver(n)},_a=function(){return e(this,void 0,void 0,function*(){i(this,ua,"f")||n(this,ua,new Ko,"f"),i(this,ua,"f").enableResultCrossVerification(2,!0),i(this,ua,"f").enableResultDeduplication(2,!0),i(this,ua,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(i(this,ua,"f")),i(this,ua,"f").isResultCrossVerificationEnabled=()=>!1,i(this,ua,"f").isResultDeduplicationEnabled=()=>!1})},va=function(e){const n=this._cameraView.getUIElement().shadowRoot;let r=new Promise(t=>{if(e.decodedBarcodesResult.barcodeResultItems.length>1){i(this,ia,"m",Ea).call(this);for(let i of e.decodedBarcodesResult.barcodeResultItems){let e=0,r=0;for(let t=0;t<4;++t){let n=i.location.points[t];e+=n.x,r+=n.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{t(i)}),n.append(o)}}else t(e.decodedBarcodesResult.barcodeResultItems[0])});r.then(n=>{const r=e.items.filter(t=>t.type===ht.CRIT_ORIGINAL_IMAGE)[0].imageData,s={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},originalImageResult:r,barcodeImage:(()=>{const t=U(r),e=n.location.points,i=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-i,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-i,e[0].y-s);for(let t=1;t<e.length;t++)u.lineTo(e[t].x-i,e[t].y-s);u.closePath(),u.clip(),u.drawImage(t,-i,-s);const d=u.getImageData(0,0,c.width,c.height);return{bytes:new Uint8Array(d.data),width:d.width,height:d.height,stride:4*d.width,format:v.IPF_ARGB_8888}})(),barcodeResults:[n]};i(this,ia,"m",xa).call(this,n),i(Ra,na,"f",ra).resolve(s),this.dispose()})},ya=function(t){for(let e of t.decodedBarcodesResult.barcodeResultItems){if(!1!==e.duplicate)continue;const t=i(this,oa,"f").barcodeResults.findIndex(t=>`${t.formatString}_${t.text}`==`${e.formatString}_${e.text}`);-1===t?(e.count=1,i(this,oa,"f").barcodeResults.unshift(e),i(this,ia,"m",Ca).call(this,e)):(i(this,oa,"f").barcodeResults[t].count++,i(this,ia,"m",Sa).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(e)}},wa=function(t){const e=i(this,ha,"f").cloneNode(!0);e.querySelector(".format-string").innerText=t.formatString;e.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),e.id=`${t.formatString}_${t.text}`;return e.querySelector(".delete-icon").addEventListener("click",()=>{const e=[...document.querySelectorAll(".main-list .result-item")],n=e.findIndex(e=>e.id===`${t.formatString}_${t.text}`);i(this,oa,"f").barcodeResults.splice(n,1),e[n].remove(),0===i(this,oa,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),e},Ea=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Ca=function(e){if(!this.config.showResultView)return;const n=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==t.EnumScanMode.SM_SINGLE))return;const r=document.querySelector(".main-list");if(!e)return r.textContent="",void(this.config.showPoweredByDynamsoft&&(n.style.display=""));n.style.display="none";const s=i(this,ia,"m",wa).call(this,e);r.insertBefore(s,document.querySelector(".result-item"))},Sa=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},ba=function(n){n||(n=document.querySelector(".btn-upload-image")),n&&(n.style.display="",n.onchange=n=>e(this,void 0,void 0,function*(){const e=n.target.files,r={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]};let s=0;i(this,ia,"m",Ia).call(this,`Capturing... [${s}/${e.length}]`,!0);let o=!1;for(let t=0;t<e.length;t++)if(!ao(e[t])){o=!0;break}if(o)return i(Ra,na,"f",ra).reject(new Error("Upload failed: one or more files are in unsupported formats. Please make sure all files are .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp.")),void this.dispose();for(let n of e)try{const o=yield this.decode(n,this.config.utilizedTemplateNames.image);if(o.decodedBarcodesResult)if(this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE)for(let t of o.decodedBarcodesResult.barcodeResultItems){const e=i(this,oa,"f").barcodeResults.findIndex(e=>`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===e?(t.count=1,i(this,oa,"f").barcodeResults.unshift(t),i(this,ia,"m",Ca).call(this,t)):(i(this,oa,"f").barcodeResults[e].count++,i(this,ia,"m",Sa).call(this,e))}else if(o.decodedBarcodesResult.barcodeResultItems)for(let t of o.decodedBarcodesResult.barcodeResultItems){const e=r.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,r.barcodeResults.push(t))}i(this,ia,"m",Ia).call(this,`Capturing... [${++s}/${e.length}]`,!0)}catch(e){r.status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(Ra,na,"f",ra).reject(new Error(r.status.message)),this.dispose()}i(this,ia,"m",Ia).call(this,"Loading...",!1),this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(i(Ra,na,"f",ra).resolve(r),this.dispose()),n.target.value=""}))},Ta=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},Ia=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},xa=function(t){let e=Rt();At[e]=()=>{},xt.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},ra={value:null};const Aa="undefined"==typeof self,Da="function"==typeof importScripts,La=(()=>{if(!Da){if(!Aa&&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"./"}})(),Ma=t=>{if(null==t&&(t="./"),Aa||Da);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};jt.engineResourcePaths.dbr={version:"11.0.60-dev-20250812165905",path:La,isInternal:!0},Nt.dbr={js:!1,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},kt.dbr={};const Fa="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,Fa)<0&&(jt.engineResourcePaths.std={version:Fa,path:Ma(La+`../../dynamsoft-capture-vision-std@${Fa}/dist/`),isInternal:!0});const Pa="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,Pa)<0)&&(jt.engineResourcePaths.dip={version:Pa,path:Ma(La+`../../dynamsoft-image-processing@${Pa}/dist/`),isInternal:!0});const ka={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),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_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Na,Ba,ja,Ua;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(Na||(Na={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Ba||(Ba={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(ja||(ja={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(Ua||(Ua={}));var Va,Ga,Wa=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=Pt.dbr&&Pt.dbr.wasm;return`11.0.60-dev-20250812165905(Worker: ${Pt.dbr&&Pt.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:ka,get EnumDeblurMode(){return Ua},get EnumExtendedBarcodeResultType(){return Na},get EnumLocalizationMode(){return ja},get EnumQRCodeErrorCorrectionLevel(){return Ba}});function Ya(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Ha(e,t,"map"),t.getFieldRawValue=t=>Ha(e,t,"raw"),t.getFieldMappingStatus=t=>Xa(e,t),t.getFieldValidationStatus=t=>za(e,t),delete t.fullCodeString}function Ha(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=Ha(r,e,i);if(void 0!==t)return t}}}function Xa(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Va[i.MappingStatus]):Va.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=Xa(n,e);if(void 0!==t)return t}}}function za(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(Ga[i.ValidationStatus]):Ga.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=za(n,e);if(void 0!==t)return t}}}function qa(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"}(Va||(Va={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(Ga||(Ga={}));const Ka=t=>t&&"object"==typeof t&&"function"==typeof t.then,Za=(async()=>{})().constructor;class Ja extends Za{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,Ka(t)?e=t:"function"==typeof t&&(e=new Za(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&&(Ka(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class $a{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!kt.license)throw Error("Module `license` is not existed.");await kt.license.dynamsoft(),await jt.loadWasm();const t=new $a,e=new Ja;let i=Rt();return At[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},xt.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){qa(this);let t=Rt();this.bDestroyed=!0,At[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},xt.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(qa(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await k(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Rt();At[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)}},xt.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return qa(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(qa(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=Rt();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i<t.length;++i)e.push(t.charCodeAt(i));return e}(t))),At[r]=async t=>{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(Ya(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},xt.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const Qa="undefined"==typeof self,th="function"==typeof importScripts,eh=(()=>{if(!th){if(!Qa&&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"./"}})();jt.engineResourcePaths.dcp={version:"3.0.60-dev-20250812165958",path:eh,isInternal:!0},Nt.dcp={js:!0,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE]},kt.dcp={handleParsedResultItem:Ya};const ih="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,ih)<0&&(jt.engineResourcePaths.std={version:ih,path:(t=>{if(null==t&&(t="./"),Qa||th);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(eh+`../../dynamsoft-capture-vision-std@${ih}/dist/`),isInternal:!0});var nh=Object.freeze({__proto__:null,CodeParser:$a,CodeParserModule:class{static getVersion(){const t=Pt.dcp&&Pt.dcp.wasm;return`3.0.60-dev-20250812165958(Worker: ${Pt.dcp&&Pt.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await jt.loadWasm(),await new Promise((i,n)=>{let r=Rt();At[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],o=B(jt.engineResourcePaths);xt.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===jt._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}},get EnumMappingStatus(){return Va},get EnumValidationStatus(){return Ga}});jt._bundleEnv="DBR",Ne._defaultTemplate="ReadSingleBarcode",jt.engineResourcePaths.dbrBundle={version:"11.0.6000",path:o,isInternal:!0},t.BarcodeScanner=Ra,t.CVR=Ue,t.Core=Ut,t.DBR=Wa,t.DCE=Ls,t.DCP=nh,t.License=eo,t.Utility=Oa});