-
+
+
```
- UNPKG
```html
-
+
```
#### Host the SDK yourself
@@ -165,24 +170,24 @@ Options to download the SDK:
- From the website
- Download the JavaScript Package
+ Download the JavaScript Package
-- yarn
+- npm
```cmd
- yarn add dynamsoft-javascript-barcode
+ npm i dynamsoft-javascript-barcode -E
```
-- npm
+- yarn
```cmd
- npm install dynamsoft-javascript-barcode --save
+ yarn add dynamsoft-javascript-barcode -E
```
Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this:
```html
-
+
```
or
@@ -193,7 +198,7 @@ or
or
-```ts
+```typescript
import { BarcodeScanner } from 'dynamsoft-javascript-barcode';
```
@@ -224,7 +229,7 @@ The SDK requires a license to work, use the API `license` to specify a license k
Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY";
```
-To test the SDK, you can request a 30-day trial license via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?ver=9.6.32&utm_source=github&product=dbr&package=js).
+To test the SDK, you can request a 30-day trial license via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?ver=9.6.42&utm_source=github&product=dbr&package=js).
> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK.
@@ -236,7 +241,7 @@ The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.
```javascript
//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files
-Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.32/dist/";
+Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/";
```
### Interact with the SDK
@@ -331,9 +336,9 @@ As you can see from the above code snippets, there are three types of configurat
Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/).
- See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.32&utm_source=github).
+ See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.42&utm_source=github).
-> Find the full list of the runtime settings here.
+> Find the full list of the runtime settings here.
### Customize the UI (optional)
@@ -417,8 +422,8 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.
```html
```
@@ -431,7 +436,7 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.
## API Documentation
You can check out the detailed documentation about the APIs of the SDK at
-[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.32](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.32).
+[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.42](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.42).
## System Requirements
@@ -452,7 +457,7 @@ DBR requires the following features to work:
- `MediaDevices`/`getUserMedia`
- This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.32&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera.
+ This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.42&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera.
- `getSettings`
@@ -477,7 +482,7 @@ Apart from the browsers, the operating systems may impose some limitations of th
## How to Upgrade
-If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.32&utm_source=github).
+If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.42&utm_source=github).
## Release Notes
diff --git a/dist/dbr-9.6.32.browser.worker.js b/dist/dbr-9.6.32.browser.worker.js
deleted file mode 100644
index 2031c10..0000000
--- a/dist/dbr-9.6.32.browser.worker.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/*!
- * Dynamsoft JavaScript Library
- * @product Dynamsoft Barcode Reader JS Edition
- * @website http://www.dynamsoft.com
- * @copyright Copyright 2023, Dynamsoft Corporation
- * @author Dynamsoft
- * @version 9.6.32 (js 20231027)
- * @fileoverview Dynamsoft JavaScript Library for Barcode Reader
- * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/
- */
-!function(){"use strict";const e="undefined"==typeof self,t=e?{}:self,r=e=>e&&"object"==typeof e&&"function"==typeof e.then;class n extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(r(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,r(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}let o,a,s,i,c;if("undefined"!=typeof navigator&&(o=navigator,a=o.userAgent,s=o.platform,i=o.mediaDevices),!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:o.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:s,search:"Win"},Mac:{str:s},Linux:{str:s}};let r="unknownBrowser",n=0,i="unknownOS";for(let t in e){const o=e[t]||{};let s=o.str||a,i=o.search||t,c=o.verStr||a,d=o.verSearch||t;if(d instanceof Array||(d=[d]),-1!=s.indexOf(i)){r=t;for(let e of d){let t=c.indexOf(e);if(-1!=t){n=parseFloat(c.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let n=r.str||a,o=r.search||e;if(-1!=n.indexOf(o)){i=e;break}}"Linux"==i&&-1!=a.indexOf("Windows NT")&&(i="HarmonyOS"),c={browser:r,version:n,OS:i}}e&&(c={browser:"ssr",version:0,OS:"ssr"}),"undefined"!=typeof WebAssembly&&a&&(!/Safari/.test(a)||/Chrome/.test(a)||/\(.+\s11_2_([2-6]).*\)/.test(a)),i&&i.getUserMedia;const d="Chrome"===c.browser&&c.version>66||"Safari"===c.browser&&c.version>13||"OPR"===c.browser&&c.version>43||"Edge"===c.browser&&c.version>15;var u=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function l(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(o){if("TypeError"!==o.name)throw o;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}})).catch((function(){return!1}))}(e).then((function(e){return p=e,p}))}function k(e){var t=b[e.name],r={};r.promise=new Promise((function(e,t){r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((function(){return r.promise})):t.dbReady=r.promise}function I(e){var t=b[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function M(e,t){var r=b[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function x(e,t){return new Promise((function(r,n){if(b[e.name]=b[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);k(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var a=u.open.apply(u,o);t&&(a.onupgradeneeded=function(t){var r=a.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(y)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),n(a.error)},a.onsuccess=function(){var t=a.result;t.onversionchange=function(e){e.target.close()},r(t),I(e)}}))}function C(e){return x(e,!1)}function P(e){return x(e,!0)}function D(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||r){if(r){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function N(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),o=0;o0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),P(e)})).then((()=>function(e){k(e);for(var t=b[e.name],r=t.forages,n=0;n(e.db=t,D(e)?P(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw M(e,t),t}))}(e).then((function(){T(e,t,r,n-1)})))).catch(r);r(o)}}var E={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=b[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},b[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=R);var a=[];function s(){return Promise.resolve()}for(var i=0;i{const r=b[e.name],n=r.forages;r.db=t;for(var o=0;o{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;k(e);const n=b[e.name],o=n.forages;t.close();for(let e=0;e{const o=u.open(e.name,r);o.onerror=e=>{o.result.close(),n(e)},o.onupgradeneeded=()=>{o.result.deleteObjectStore(e.storeName)},o.onsuccess=()=>{const e=o.result;e.close(),t(e)}}));return a.then((e=>{n.db=e;for(let t=0;t{throw(M(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{k(e);const r=b[e.name],n=r.forages;t.close();for(var o=0;o{var n=u.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}}));return a.then((e=>{r.db=e;for(var t=0;t{throw(M(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else n=Promise.reject("Invalid arguments");return f(n,t),n}};const O=new Map;function B(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var F={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=B(e,this._defaultConfig);this._dbInfo=t,O.has(r)||O.set(r,new Map)},getItem:function(e,t){e=h(e);const r=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).get(e)));return f(r,t),r},setItem:function(e,t,r){e=h(e);const n=this.ready().then((()=>(void 0===t&&(t=null),O.get(this._dbInfo.keyPrefix).set(e,t),t)));return f(n,r),n},removeItem:function(e,t){e=h(e);const r=this.ready().then((()=>{O.get(this._dbInfo.keyPrefix).delete(e)}));return f(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;O.has(e)&&O.delete(e)}));return f(t,e),t},length:function(e){const t=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).size));return f(t,e),t},keys:function(e){const t=this.ready().then((()=>[...O.get(this._dbInfo.keyPrefix).keys()]));return f(t,e),t},dropInstance:function(e,t){if(t=g.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise((t=>{e.storeName?t(B(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{O.delete(e)})):Promise.reject("Invalid arguments"),f(r,t),r}};const A=(e,t)=>{const r=e.length;let n=0;for(;n{}))}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise((function(t,r){try{const n=e._driver,o=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(o);const a=L.concat("_initStorage");for(let t=0,n=a.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return m(r,e,e),r}setDriver(e,t,r){const n=this;j(e)||(e=[e]);const o=this._getSupportedDrivers(e);function a(){n._config.driver=n.driver()}function s(e){return n._extend(e),a(),n._ready=n._initStorage(n._config),n._ready}const i=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=i.then((()=>{const e=o[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then((e=>{n._driver=e._driver,a(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{a();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet})),m(this._driverSet,t,r),this._driverSet}supports(e){return!!J[e]}_extend(e){K(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let r,o,a,s,i,c,u,l,f,m=t.btoa,h=t.atob,g=e.bd,y=e.dm;const p=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"];let b,v,w,S,_,k,I,M,x,C,P,D,N,R,T,E=p,O=!1,B=Promise.resolve(),F=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),A=g&&F||(()=>{}),j=e=>e.join(""),U={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},J=()=>t[j(U.c)][j(U.e)][j(U.f)]("raw",new Uint8Array(U.a.concat(U.b,U.d,U.k)),j(U.g),!0,[j(U.h),j(U.i)]),W=e=>h(h(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),z=e=>m(String.fromCharCode(97+25*Math.random())+m(e)).replace(/\+/g,"\n").replace(/=/g," "),H=()=>{if(t.crypto){let e=new Uint8Array(36);t.crypto.getRandomValues(e);let r="";for(let t=0;t<36;++t){let n=e[t]%36;r+=n<10?n:String.fromCharCode(n+87)}return r}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))};const L="Failed to connect to the Dynamsoft License Server: ",$={dlsErrorAndCacheExpire:L+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:L+"network timed out. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",networkTimeout:L+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:L+"network connection error. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",failConnect:L+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again.",idbTimeout:"Failed to open indexedDB: Timeout."};let V,K,Z,X,Y=async()=>{if(V)return V;V=new n,await(async()=>{I||(I=G)})(),await Promise.race([(async()=>{let e=await I.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise(((e,t)=>{setTimeout((()=>t(new Error($.idbTimeout))),5e3)}))]),x=await I.createInstance({name:"dynamdlsinfo"}),C=m(m("v2")+String.fromCharCode(y.charCodeAt(y.length/2)+1)+m(y));try{let e=await x.getItem(C);if(!e){let t=await I.createInstance({name:"dynamltsinfo"});e=await t.getItem(C),e&&await x.setItem(C,e)}e&&([u,_]=JSON.parse(await W(e)))}catch(e){}try{null==u&&(u=H(),x.setItem(C,await z(JSON.stringify([u,null]))))}catch(e){}V.resolve()},q=async()=>{P=m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+a+m(""+c)),M=await I.createInstance({name:"dynamdlsuns"+m(m("v2"))+m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+a+m(""+c))});try{i=await x.getItem(P)}catch(e){}j=e=>h(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))},Q=async e=>{if(Z=Date.now(),K)return K;K=new n;try{let t={pd:r,vm:a,v:o,dt:c||"browser",ed:"javascript",cu:u,ad:y,os:l,fn:f};w&&(t.rmk=w),s&&(-1!=s.indexOf("-")?t.hs=s:t.og=s);let n={};if(_){let e=await x.getItem(C);e&&([u,_]=JSON.parse(await W(e))),n["lts-time"]=_}v&&(t.sp=v);let d=await Promise.race([(async()=>{let r,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");_&&(x.setItem(C,await z(JSON.stringify([u,o]))),_=o);let a="auth/?ext="+encodeURIComponent(m(JSON.stringify(t)));S&&(a+="&v="+encodeURIComponent(S));let s,c=!1,d=!1,l=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(s=e,e.errorCode>100&&e.errorCode<200&&(i=null,c=!0,d=!0))}}catch(e){}};try{r=await Promise.race([fetch(E[0]+a,{headers:n,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await l(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(E[1]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(E[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(r)}catch(e){}s&&151==s.errorCode&&(x.removeItem(C),x.removeItem(P),u=H(),t.cu=u,_=void 0,a="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),r=await Promise.race([fetch(E[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(r));(()=>{if(!r||!r.ok){let e;d&&x.setItem(P,""),s?111==s.errorCode?e=s.message:(e=s.message.trim(),e.endsWith(".")||(e+="."),e=b?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=b?$.publicTrialFailConnect:$.failConnect;let t=Error(e);throw s&&s.errorCode&&(t.ltsErrorCode=s.errorCode),t}})();let f=await r.text();try{_||(x.setItem(C,await z(JSON.stringify([u,o]))),_=o),x.setItem(P,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=b?$.publicTrialNetworkTimeout:$.networkTimeout,setTimeout((()=>t(new Error(r))),i?3e3:15e3)}))]);i=d}catch(e){g&&console.error(e),k=e}K.resolve(),K=null},ee=async()=>{X||(X=(async()=>{if(A(u),!i){if(!O)throw F(k.message),k;return}let e={dm:y};g&&(e.bd=!0),e.brtk=!0,e.ls=E[0],s&&(-1!=s.indexOf("-")?e.hs=s:e.og=s),e.cu=u,f&&(e.fn=f),r&&(e.pd=r),o&&(e.v=o),c&&(e.dt=c),l&&(e.os=l),w&&(e.rmk=w),A(i);try{let r=JSON.parse(await(async e=>{if(t[j(U.c)]&&t[j(U.c)][j(U.e)]&&t[j(U.c)][j(U.e)][j(U.f)]){let r=h(e),n=new Uint8Array(r.length);for(let e=0;e{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await R();if(A(t),t&&t(B=B.then((async()=>{try{let r=await M.keys();if(t||(re.isFulfilled?e&&(r=r.filter((t=>t{r=e.pd,o=e.v,a=o.split(".")[0],e.dt&&(c=e.dt),s=e.l||"",l="string"!=typeof e.os?JSON.stringify(e.os):e.os,f=e.fn,"string"==typeof f&&(f=f.substring(0,50)),e.ls&&e.ls.length&&(E=e.ls,1==E.length&&E.push(E[0])),b=p===E&&(!s||"200001"===s||s.startsWith("200001-")),v=e.sp,w=e.rmk,e.cv&&(S=""+e.cv),D=e.updl,N=e.mnet,R=e.mxet,await Y(),await q(),await Q(),await ee(),(!k||k.ltsErrorCode>=102&&k.ltsErrorCode<=120)&&oe(null,!0)},c:async()=>{let e=new Date;if(e.getTime()ee()))}},s:async(e,r,n,o)=>{try{let e;e=r.startsWith("{")&&r.endsWith("}")?await(async e=>{if(t[j(U.c)]&&t[j(U.c)][j(U.e)]&&t[j(U.c)][j(U.e)][j(U.f)]){let r=new Uint8Array(e.length);for(let t=0;t{await oe()}),36e4)},p:re,u:async()=>(await Y(),u)}},oe=t,ae="dbr",se=!1,ie="BarcodeReaderWasm",ce=0,de=0;let ue=new n,le=!1,fe=async e=>{await ue,ee=e.trial,te=e.msg,Module[ie].init(JSON.stringify(e))},me=()=>{let e=Module[ie].getMinExpireTime;return e?e():null},he=()=>{let e=Module[ie].getMaxExpireTime;return e?e():null},ge=new Map,ye=0,pe=!1,be=async function(e){const r=e.data?e.data:e,n=r.id,o=r.instanceID,a=r.body;switch(!Q||"decodeBuffer"!=r.type&&"decodeFileInMemory"!=r.type||await re.c(),r.type){case"loadWasm":try{X=r.bd,Y=r.engineResourcePath,se=r.bUseFullFeature,q=r.v;let e=r.dm,n=r.l;Q=r.brtk;let o,a=r.bptk;(async()=>{if(le)throw"can't load wasm twice";le=!0,ve("wasm loading...");let e=Date.now();await new Promise((async e=>{t.KModule=t.Module={locateFile:function(e){return["dbr.full.wasm.wasm","dbr.wasm.wasm"].includes(e)?"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm":Y+ae+"-"+q+(se?".full":"")+".wasm":Y+e},print:e=>{ve(e)},printErr:e=>{console.error(e),ve(e)},onRuntimeInitialized:e},"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?importScripts(Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm.js"):importScripts(Y+ae+"-"+q+(se?".full":"")+".wasm.js")})),ve("wasm initialized, cost "+(Date.now()-e)+" ms"),Module=KModule,ue.resolve()})();let s=async()=>{try{re=ne({log:ve,bd:X,dm:e}),t.scsd=re.s,r.pd="dbr",r.updl=fe,r.mnet=me,r.mxet=he,await re.i(r)}catch(e){if(!a)throw e;Q=!1,await i(),o=e.ltsErrorCode,te=e.message||e}},i=async()=>{let t={pk:n,dm:e};X&&(t.bd=!0),await fe(t)};Q?await s():await i(),oe.postMessage({type:"load",success:!0,version:Module[ie].getVersion(),trial:ee,ltsErrorCode:o,message:te})}catch(e){let t=e&&e.message;oe.postMessage({type:"load",success:!1,ltsErrorCode:e&&e.ltsErrorCode,message:t,trial:ee,stack:X&&e?e.stack:null})}break;case"createInstance":{const e=ye++;try{let t=new Module[ie](r.bScanner,e);ge.set(e,t);let n=JSON.parse(t.getRuntimeSettings());r.bScanner?(n.expectedBarcodesCount=1,n.deblurLevel=0,n.localizationModes=[16,2,0,0,0,0,0,0]):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),se||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,instanceID:e}});break}case"destroyContext":try{if(!ge.get(o))break;ge.get(o).delete(),ge.delete(o)}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"decodeBuffer":{let e,t,r,s,i=Date.now();try{e=X?Date.now():0,d=a.buffer,(u=a.stride*a.height)>ce&&(de&&Module._free(de),de=Module._malloc(u),ce=u),Module.HEAPU8.set(d.subarray(0,u),de),t=X?Date.now():0,s=JSON.parse(ge.get(o).decodeBufferPtr(de,a.width,a.height,a.stride,a.format,void 0===a.orientation?0:a.orientation,!(!a.config||!a.config.bScanner))),r=Date.now()}catch(e){Se(e,n);break}!pe&&Q&&re.p.isPending&&(await Promise.race([re.p,new Promise((e=>setTimeout(e,500)))]),pe=!0),oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:s,buffer:a.buffer,duration:Date.now()-i}},[a.buffer.buffer]),we(["timeWorkerGetMsg: "+i,"timeBeforeSendBufferToWasm: "+e+" "+(e-i),"timeBeforeDecode: "+t+" "+(t-e),"timeFinishDecode: "+r+" "+(r-t)].join("\n"));break}case"decodeFileInMemory":{let e,t,r;try{t=X?Date.now():0,e=JSON.parse(ge.get(o).decodeFileInMemory(a.bytes)),r=X?Date.now():0}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:e,duration:r-t}});break}case"clearMapDecodeRecord":try{ge.get(o).clearMapDecodeRecord()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getRuntimeSettings":{let e;try{e=ge.get(o).getRuntimeSettings()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"updateRuntimeSettings":{let e;try{e=JSON.parse(ge.get(o).updateRuntimeSettings(a.settings))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,updateReturn:e}});break}case"resetRuntimeSettings":try{let e=ge.get(o);e.resetRuntimeSettings();let t=JSON.parse(e.getRuntimeSettings());e.bScanner?(t.expectedBarcodesCount=1,t.deblurLevel=0,t.localizationModes=[16,2,0,0,0,0,0,0]):(t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.timeout=1e5),se||(t.barcodeFormatIds=238028799),e.updateRuntimeSettings(JSON.stringify(t)),e.bScanner&&(e.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),e.setModeArgument("LocalizationModes",0,"ScanDirection","2"),e.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),e.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}catch(t){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"resetRuntimeSettingsToCppDefault":try{ge.get(o).resetRuntimeSettings()}catch(t){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"outputRuntimeSettingsToString":{let e;try{e=ge.get(o).outputSettingsToString()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"initRuntimeSettingsWithString":{let e;try{e=JSON.parse(ge.get(o).initRuntimeSettingsWithString(a.settings))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,initReturn:e}});break}case"getIntermediateResults":{let e=[];try{var s=ge.get(o).getIntermediateResults(a.isCharge),i=JSON.parse(s,((t,r)=>{if("bytes"===t&&"ptr"in r&&"length"in r){var n=r,o=n.ptr,a=n.length;let t=Module[ie].getBytes(o,a);return t=t.slice(0),e.push(t.buffer),t}return r}))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:i}},e),ge.get(o).freeIntermediateResults();break}case"setModeArgument":{let e;try{e=JSON.parse(ge.get(o).setModeArgument(a.modeName,a.index,a.argumentName,a.argumentValue))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,setReturn:e}});break}case"getModeArgument":{let e;try{e=JSON.parse(ge.get(o).getModeArgument(a.modeName,a.index,a.argumentName))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,getReturn:e}});break}case"updateScanSettings":try{let e=ge.get(o),t=a.settings;e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getScanSettings":{let e={};try{let t=ge.get(o);e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}default:console.warn("Unmatched task: ",e)}var d,u};oe.onmessage=be;let ve=e=>{oe.postMessage({type:"log",message:e})},we=e=>{X&&ve(e)},Se=(e,t)=>{oe.postMessage({type:"task",id:t,body:{success:!1,message:e.message,stack:e.stack}}),setTimeout((()=>{throw e}),0)}}();
diff --git a/dist/dbr-9.6.42.browser.worker.js b/dist/dbr-9.6.42.browser.worker.js
new file mode 100644
index 0000000..a51398b
--- /dev/null
+++ b/dist/dbr-9.6.42.browser.worker.js
@@ -0,0 +1,11 @@
+/*!
+ * Dynamsoft JavaScript Library
+ * @product Dynamsoft Barcode Reader JS Edition
+ * @website http://www.dynamsoft.com
+ * @copyright Copyright 2024, Dynamsoft Corporation
+ * @author Dynamsoft
+ * @version 9.6.42 (js 20240426)
+ * @fileoverview Dynamsoft JavaScript Library for Barcode Reader
+ * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/
+ */
+!function(){"use strict";const e="undefined"==typeof self,t=e?{}:self,r=e=>e&&"object"==typeof e&&"function"==typeof e.then;class n extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(r(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,r(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}let o,a,s,i,c;"undefined"!=typeof navigator&&(o=navigator,a=o.userAgent,s=o.platform,i=o.mediaDevices),function(){if(!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:o.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:s,search:"Win"},Mac:{str:s},Linux:{str:s}};let r="unknownBrowser",n=0,i="unknownOS";for(let t in e){const o=e[t]||{};let s=o.str||a,i=o.search||t,c=o.verStr||a,d=o.verSearch||t;if(d instanceof Array||(d=[d]),-1!=s.indexOf(i)){r=t;for(let e of d){let t=c.indexOf(e);if(-1!=t){n=parseFloat(c.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let n=r.str||a,o=r.search||e;if(-1!=n.indexOf(o)){i=e;break}}"Linux"==i&&-1!=a.indexOf("Windows NT")&&(i="HarmonyOS"),c={browser:r,version:n,OS:i}}e&&(c={browser:"ssr",version:0,OS:"ssr"})}(),i&&i.getUserMedia;const d="Chrome"===c.browser&&c.version>66||"Safari"===c.browser&&c.version>13||"OPR"===c.browser&&c.version>43||"Edge"===c.browser&&c.version>15;var l=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function u(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(o){if("TypeError"!==o.name)throw o;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}})).catch((function(){return!1}))}(e).then((function(e){return p=e,p}))}function _(e){var t=b[e.name],r={};r.promise=new Promise((function(e,t){r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((function(){return r.promise})):t.dbReady=r.promise}function I(e){var t=b[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function x(e,t){var r=b[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function M(e,t){return new Promise((function(r,n){if(b[e.name]=b[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);_(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var a=l.open.apply(l,o);t&&(a.onupgradeneeded=function(t){var r=a.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(y)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),n(a.error)},a.onsuccess=function(){var t=a.result;t.onversionchange=function(e){e.target.close()},r(t),I(e)}}))}function C(e){return M(e,!1)}function D(e){return M(e,!0)}function P(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||r){if(r){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function N(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),o=0;o0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),D(e)})).then((()=>function(e){_(e);for(var t=b[e.name],r=t.forages,n=0;n(e.db=t,P(e)?D(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw x(e,t),t}))}(e).then((function(){T(e,t,r,n-1)})))).catch(r);r(o)}}var O={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=b[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},b[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=R);var a=[];function s(){return Promise.resolve()}for(var i=0;i{const r=b[e.name],n=r.forages;r.db=t;for(var o=0;o{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;_(e);const n=b[e.name],o=n.forages;t.close();for(let e=0;e{const o=l.open(e.name,r);o.onerror=e=>{o.result.close(),n(e)},o.onupgradeneeded=()=>{o.result.deleteObjectStore(e.storeName)},o.onsuccess=()=>{const e=o.result;e.close(),t(e)}}));return a.then((e=>{n.db=e;for(let t=0;t{throw(x(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{_(e);const r=b[e.name],n=r.forages;t.close();for(var o=0;o{var n=l.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}}));return a.then((e=>{r.db=e;for(var t=0;t{throw(x(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else r=Promise.reject("Invalid arguments");return f(r,t),r}};const E=new Map;function B(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var F={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=B(e,this._defaultConfig);this._dbInfo=t,E.has(r)||E.set(r,new Map)},getItem:function(e,t){e=h(e);const r=this.ready().then((()=>E.get(this._dbInfo.keyPrefix).get(e)));return f(r,t),r},setItem:function(e,t,r){e=h(e);const n=this.ready().then((()=>(void 0===t&&(t=null),E.get(this._dbInfo.keyPrefix).set(e,t),t)));return f(n,r),n},removeItem:function(e,t){e=h(e);const r=this.ready().then((()=>{E.get(this._dbInfo.keyPrefix).delete(e)}));return f(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;E.has(e)&&E.delete(e)}));return f(t,e),t},length:function(e){const t=this.ready().then((()=>E.get(this._dbInfo.keyPrefix).size));return f(t,e),t},keys:function(e){const t=this.ready().then((()=>[...E.get(this._dbInfo.keyPrefix).keys()]));return f(t,e),t},dropInstance:function(e,t){if(t=g.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise((t=>{e.storeName?t(B(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{E.delete(e)})):Promise.reject("Invalid arguments"),f(r,t),r}};const j=(e,t)=>{const r=e.length;let n=0;for(;n{}))}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise((function(t,r){try{const n=e._driver,o=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(o);const a=L.concat("_initStorage");for(let t=0,n=a.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return m(r,e,e),r}setDriver(e,t,r){const n=this;A(e)||(e=[e]);const o=this._getSupportedDrivers(e);function a(){n._config.driver=n.driver()}function s(e){return n._extend(e),a(),n._ready=n._initStorage(n._config),n._ready}const i=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=i.then((()=>{const e=o[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then((e=>{n._driver=e._driver,a(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{a();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet})),m(this._driverSet,t,r),this._driverSet}supports(e){return!!J[e]}_extend(e){Z(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let r,o,a,s,i,c,l,u,f,m,h,g,y,p,b,v,w,S,k,_,I,x,M,C,D=t.btoa,P=t.atob,N=e.bd,R=e.dm,T=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"],O=!1,E=Promise.resolve(),B=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),F=N&&B||(()=>{}),j=e=>e.join(""),A={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},U=()=>t[j(A.c)][j(A.e)][j(A.f)]("raw",new Uint8Array(A.a.concat(A.b,A.d,A.k)),j(A.g),!0,[j(A.h),j(A.i)]),J=async e=>{if(t[j(A.c)]&&t[j(A.c)][j(A.e)]&&t[j(A.c)][j(A.e)][j(A.f)]){let r=P(e),n=new Uint8Array(r.length);for(let e=0;eP(P(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),W=e=>D(String.fromCharCode(97+25*Math.random())+D(e)).replace(/\+/g,"\n").replace(/=/g," "),H=()=>{if(t.crypto){let e=new Uint8Array(36);t.crypto.getRandomValues(e);let r="";for(let t=0;t<36;++t){let n=e[t]%36;r+=n<10?n:String.fromCharCode(n+87)}return r}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))};const L="Failed to connect to the Dynamsoft License Server: ",$=" Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license.",V={dlsErrorAndCacheExpire:L+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:L+"network timed out."+$,networkTimeout:L+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:L+"network connection error."+$,failConnect:L+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again.",idbTimeout:"Failed to open indexedDB: Timeout.",dlsOfflineLicenseExpired:"The DLS2 Offline license has expired. Please contact the site administrator for more information."};let Z,K,X,Y,q=async()=>{if(Z)return Z;Z=new n,await(async()=>{v||(v=G)})(),await Promise.race([(async()=>{let e=await v.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise(((e,t)=>{setTimeout((()=>t(new Error(V.idbTimeout))),5e3)}))]),S=await v.createInstance({name:"dynamdlsinfo"}),k=D(D("v2")+String.fromCharCode(R.charCodeAt(R.length/2)+1)+D(R));try{let e=await S.getItem(k);if(!e){let t=await v.createInstance({name:"dynamltsinfo"});e=await t.getItem(k),e&&await S.setItem(k,e)}e&&([l,p]=JSON.parse(await z(e)))}catch(e){}try{null==l&&(l=H(),S.setItem(k,await W(JSON.stringify([l,null]))))}catch(e){}Z.resolve()},Q=async e=>{if(X=Date.now(),K)return K;K=new n;try{let t={pd:r,vm:a,v:o,dt:c||"browser",ed:"javascript",cu:l,ad:R,os:u,fn:f};g&&(t.rmk=g),s&&(-1!=s.indexOf("-")?t.hs=s:t.og=s);let n={};if(p){let e=await S.getItem(k);e&&([l,p]=JSON.parse(await z(e))),n["lts-time"]=p}h&&(t.sp=h);let d=await Promise.race([(async()=>{let r,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");p&&(S.setItem(k,await W(JSON.stringify([l,o]))),p=o);let a="auth/?ext="+encodeURIComponent(D(JSON.stringify(t)));y&&(a+="&"+encodeURIComponent(y));let s,c=!1,d=!1,u=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(s=e,e.errorCode>100&&e.errorCode<200&&(i=null,c=!0,d=!0))}}catch(e){}};try{r=await Promise.race([fetch(T[0]+a,{headers:n,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await u(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(T[1]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))])}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(T[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)}catch(e){}s&&151==s.errorCode&&(S.removeItem(k),S.removeItem(_),l=H(),t.cu=l,p=void 0,a="auth/?ext="+encodeURIComponent(D(JSON.stringify(t))),r=await Promise.race([fetch(T[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)),(()=>{if(!r||!r.ok){let e;d&&S.setItem(_,""),s?111==s.errorCode?e=s.message:(e=s.message.trim(),e.endsWith(".")||(e+="."),e=m?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=m?V.publicTrialFailConnect:V.failConnect;let t=Error(e);throw s&&s.errorCode&&(t.ltsErrorCode=s.errorCode),t}})();let f=await r.text();try{p||(S.setItem(k,await W(JSON.stringify([l,o]))),p=o),S.setItem(_,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=m?V.publicTrialNetworkTimeout:V.networkTimeout,setTimeout((()=>t(new Error(r))),i?3e3:15e3)}))]);i=d}catch(e){N&&console.error(e),b=e}K.resolve(),K=null},ee=async()=>{Y||(Y=(async()=>{if(F(l),!i){if(!O)throw B(b.message),b;return}let e={dm:R};N&&(e.bd=!0),e.brtk=!0,e.ls=T[0],s&&(-1!=s.indexOf("-")?e.hs=s:e.og=s),e.cu=l,f&&(e.fn=f),r&&(e.pd=r),o&&(e.v=o),c&&(e.dt=c),u&&(e.os=u),g&&(e.rmk=g),F(i);try{let t=JSON.parse(await J(i));t.pv&&(e.pv=JSON.stringify(t.pv)),t.ba&&(e.ba=t.ba),t.usu&&(e.usu=t.usu),t.trial&&(e.trial=t.trial),t.its&&(e.its=t.its),1==e.trial&&t.msg?e.msg=t.msg:b?e.msg=b.message||b:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!b}catch(e){}F(e);try{await I(e)}catch(e){F("error updl")}await te(),O||(O=!0),Y=null})()),await Y},te=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await M();if(F(t),t&&t(E=E.then((async()=>{try{let r=await w.keys();if(t||(re.isFulfilled?e&&(r=r.filter((t=>t{r=e.pd,o=e.v,a=o.split(".")[0],e.dt&&(c=e.dt),s=e.l||"",u="string"!=typeof e.os?JSON.stringify(e.os):e.os,f=e.fn,"string"==typeof f&&(f=f.substring(0,255)),e.ls&&e.ls.length&&(T=e.ls,1==T.length&&T.push(T[0])),m=!s||"200001"===s||s.startsWith("200001-"),h=e.sp,g=e.rmk,"string"==typeof g&&(g=g.substring(0,255)),e.cv&&(y=""+e.cv),I=e.updl,x=e.mnet,M=e.mxet,await q(),await(async()=>{_=D(String.fromCharCode(s.charCodeAt(0)+10)+D(r)+D(s)+a+D(""+c)),w=await v.createInstance({name:"dynamdlsuns"+D(D("v2"))+D(String.fromCharCode(s.charCodeAt(0)+10)+D(r)+D(s)+a+D(""+c))});try{i=await S.getItem(_)}catch(e){}j=e=>P(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))})(),await Q(),await ee(),(!b||b.ltsErrorCode>=102&&b.ltsErrorCode<=120)&&oe(null,!0)},i2:async({updl:e,mxet:t,strDLC2:r})=>{I=e,M=t,await q(),j=e=>P(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));let n={pk:r,dm:R};N&&(n.bd=!0),n.cu=l;try{i=r.substring(4);let e=JSON.parse(await J(i));e.pv&&(n.pv=JSON.stringify(e.pv)),e.ba&&(n.ba=e.ba),n.ar=e.in}catch(e){}F(n);try{await I(n)}catch(e){F("error updl")}let o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),a=await M();if(a&&a{let e=new Date;if(e.getTime()ee()))}},s:async(e,r,n,o)=>{try{let e;e=r.startsWith("{")&&r.endsWith("}")?await(async e=>{if(t[j(A.c)]&&t[j(A.c)][j(A.e)]&&t[j(A.c)][j(A.e)][j(A.f)]){let r=new Uint8Array(e.length);for(let t=0;t{await oe()}),36e4)},p:re,u:async()=>(await q(),l),ar:()=>i,pt:()=>m,ae:()=>b}},oe=t,ae="dbr",se=!1,ie="BarcodeReaderWasm",ce=0,de=0;let le=new n,ue=!1,fe=async e=>{await le,ee=e.trial,te=e.msg,Module[ie].init(JSON.stringify(e))},me=()=>{let e=Module[ie].getMinExpireTime;return e?e():null},he=()=>{let e=Module[ie].getMaxExpireTime;return e?e():null},ge=new Map,ye=0,pe=!1;oe.onmessage=async function(e){const r=e.data?e.data:e,n=r.id,o=r.instanceID,a=r.body;switch(!Q||"decodeBuffer"!=r.type&&"decodeFileInMemory"!=r.type||await re.c(),r.type){case"loadWasm":try{X=r.bd,Y=r.engineResourcePath,se=r.bUseFullFeature,q=r.v;let e=r.dm,n=r.l;Q=r.brtk;let o,a=r.bptk;(async()=>{if(ue)throw"can't load wasm twice";ue=!0,be("wasm loading...");let e=Date.now();await new Promise((async e=>{t.KModule=t.Module={locateFile:function(e){return["dbr.full.wasm.wasm","dbr.wasm.wasm"].includes(e)?"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm":Y+ae+"-"+q+(se?".full":"")+".wasm":Y+e},print:e=>{be(e)},printErr:e=>{console.error(e),be(e)},onRuntimeInitialized:e},"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?importScripts(Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm.js"):importScripts(Y+ae+"-"+q+(se?".full":"")+".wasm.js")})),be("wasm initialized, cost "+(Date.now()-e)+" ms"),Module=KModule,le.resolve()})();let s=async()=>{try{re=ne({log:be,bd:X,dm:e}),t.scsd=re.s,r.pd="dbr",r.updl=fe,r.mnet=me,r.mxet=he,await re.i(r)}catch(e){if(!a)throw e;Q=!1,await i(),o=e.ltsErrorCode,te=e.message||e}},i=async()=>{let t={pk:n,dm:e};X&&(t.bd=!0),await fe(t)};Q?await s():await i(),oe.postMessage({type:"load",success:!0,version:Module[ie].getVersion(),trial:ee,ltsErrorCode:o,message:te})}catch(e){let t=e&&e.message;oe.postMessage({type:"load",success:!1,ltsErrorCode:e&&e.ltsErrorCode,message:t,trial:ee,stack:X&&e?e.stack:null})}break;case"createInstance":{const e=ye++;try{let t=new Module[ie](r.bScanner,e);ge.set(e,t);let n=JSON.parse(t.getRuntimeSettings());r.bScanner?(n.expectedBarcodesCount=1,n.deblurLevel=0,n.localizationModes=[16,2,0,0,0,0,0,0]):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),se||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,instanceID:e}});break}case"destroyContext":try{if(!ge.get(o))break;ge.get(o).delete(),ge.delete(o)}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"decodeBuffer":{let e,t,r,s,i=Date.now();try{e=X?Date.now():0,d=a.buffer,(l=a.stride*a.height)>ce&&(de&&Module._free(de),de=Module._malloc(l),ce=l),Module.HEAPU8.set(d.subarray(0,l),de),t=X?Date.now():0,s=JSON.parse(ge.get(o).decodeBufferPtr(de,a.width,a.height,a.stride,a.format,void 0===a.orientation?0:a.orientation,!(!a.config||!a.config.bScanner))),r=Date.now()}catch(e){we(e,n);break}!pe&&Q&&re.p.isPending&&(await Promise.race([re.p,new Promise((e=>setTimeout(e,500)))]),pe=!0),oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:s,buffer:a.buffer,duration:Date.now()-i}},[a.buffer.buffer]),ve(["timeWorkerGetMsg: "+i,"timeBeforeSendBufferToWasm: "+e+" "+(e-i),"timeBeforeDecode: "+t+" "+(t-e),"timeFinishDecode: "+r+" "+(r-t)].join("\n"));break}case"decodeFileInMemory":{let e,t,r;try{t=X?Date.now():0,e=JSON.parse(ge.get(o).decodeFileInMemory(a.bytes)),r=X?Date.now():0}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:e,duration:r-t}});break}case"clearMapDecodeRecord":try{ge.get(o).clearMapDecodeRecord()}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getRuntimeSettings":{let e;try{e=ge.get(o).getRuntimeSettings()}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"updateRuntimeSettings":{let e;try{e=JSON.parse(ge.get(o).updateRuntimeSettings(a.settings))}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,updateReturn:e}});break}case"resetRuntimeSettings":try{let e=ge.get(o);e.resetRuntimeSettings();let t=JSON.parse(e.getRuntimeSettings());e.bScanner?(t.expectedBarcodesCount=1,t.deblurLevel=0,t.localizationModes=[16,2,0,0,0,0,0,0]):(t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.timeout=1e5),se||(t.barcodeFormatIds=238028799),e.updateRuntimeSettings(JSON.stringify(t)),e.bScanner&&(e.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),e.setModeArgument("LocalizationModes",0,"ScanDirection","2"),e.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),e.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}catch(t){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"resetRuntimeSettingsToCppDefault":try{ge.get(o).resetRuntimeSettings()}catch(t){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"outputRuntimeSettingsToString":{let e;try{e=ge.get(o).outputSettingsToString()}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"initRuntimeSettingsWithString":{let e;try{e=JSON.parse(ge.get(o).initRuntimeSettingsWithString(a.settings))}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,initReturn:e}});break}case"getIntermediateResults":{let e=[];try{var s=ge.get(o).getIntermediateResults(a.isCharge),i=JSON.parse(s,((t,r)=>{if("bytes"===t&&"ptr"in r&&"length"in r){var n=r,o=n.ptr,a=n.length;let t=Module[ie].getBytes(o,a);return t=t.slice(0),e.push(t.buffer),t}return r}))}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:i}},e),ge.get(o).freeIntermediateResults();break}case"setModeArgument":{let e;try{e=JSON.parse(ge.get(o).setModeArgument(a.modeName,a.index,a.argumentName,a.argumentValue))}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,setReturn:e}});break}case"getModeArgument":{let e;try{e=JSON.parse(ge.get(o).getModeArgument(a.modeName,a.index,a.argumentName))}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,getReturn:e}});break}case"updateScanSettings":try{let e=ge.get(o),t=a.settings;e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getScanSettings":{let e={};try{let t=ge.get(o);e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}default:console.warn("Unmatched task: ",e)}var d,l};let be=e=>{oe.postMessage({type:"log",message:e})},ve=e=>{X&&be(e)},we=(e,t)=>{oe.postMessage({type:"task",id:t,body:{success:!1,message:e.message,stack:e.stack}}),setTimeout((()=>{throw e}),0)}}();
diff --git a/dist/dbr-9.6.32.full.wasm b/dist/dbr-9.6.42.full.wasm
similarity index 61%
rename from dist/dbr-9.6.32.full.wasm
rename to dist/dbr-9.6.42.full.wasm
index afb396e..88c84ea 100644
Binary files a/dist/dbr-9.6.32.full.wasm and b/dist/dbr-9.6.42.full.wasm differ
diff --git a/dist/dbr-9.6.32.full.wasm.js b/dist/dbr-9.6.42.full.wasm.js
similarity index 100%
rename from dist/dbr-9.6.32.full.wasm.js
rename to dist/dbr-9.6.42.full.wasm.js
diff --git a/dist/dbr-9.6.32.standby.full.wasm b/dist/dbr-9.6.42.standby.full.wasm
similarity index 65%
rename from dist/dbr-9.6.32.standby.full.wasm
rename to dist/dbr-9.6.42.standby.full.wasm
index 5a2af63..e7bc2e7 100644
Binary files a/dist/dbr-9.6.32.standby.full.wasm and b/dist/dbr-9.6.42.standby.full.wasm differ
diff --git a/dist/dbr-9.6.32.standby.full.wasm.js b/dist/dbr-9.6.42.standby.full.wasm.js
similarity index 99%
rename from dist/dbr-9.6.32.standby.full.wasm.js
rename to dist/dbr-9.6.42.standby.full.wasm.js
index bf41e16..7663398 100644
--- a/dist/dbr-9.6.32.standby.full.wasm.js
+++ b/dist/dbr-9.6.42.standby.full.wasm.js
@@ -456,7 +456,7 @@ function updateGlobalBufferAndViews(buf) {
Module["HEAPF64"] = HEAPF64 = new Float64Array(buf);
}
-var DYNAMIC_BASE = 7173904, DYNAMICTOP_PTR = 1930864;
+var DYNAMIC_BASE = 7170976, DYNAMICTOP_PTR = 1927936;
var INITIAL_INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216;
@@ -5739,9 +5739,9 @@ function _fd_write(fd, iov, iovcnt, pnum) {
}
}
-var ___tm_current = 1930880;
+var ___tm_current = 1927952;
-var ___tm_timezone = (stringToUTF8("GMT", 1930928, 4), 1930928);
+var ___tm_timezone = (stringToUTF8("GMT", 1928e3, 4), 1928e3);
function _gmtime_r(time, tmPtr) {
var date = new Date(HEAP32[time >> 2] * 1e3);
diff --git a/dist/dbr-9.6.32.standby.wasm b/dist/dbr-9.6.42.standby.wasm
similarity index 65%
rename from dist/dbr-9.6.32.standby.wasm
rename to dist/dbr-9.6.42.standby.wasm
index 62793c1..d20b37a 100644
Binary files a/dist/dbr-9.6.32.standby.wasm and b/dist/dbr-9.6.42.standby.wasm differ
diff --git a/dist/dbr-9.6.32.standby.wasm.js b/dist/dbr-9.6.42.standby.wasm.js
similarity index 99%
rename from dist/dbr-9.6.32.standby.wasm.js
rename to dist/dbr-9.6.42.standby.wasm.js
index 429c950..fadfb77 100644
--- a/dist/dbr-9.6.32.standby.wasm.js
+++ b/dist/dbr-9.6.42.standby.wasm.js
@@ -456,7 +456,7 @@ function updateGlobalBufferAndViews(buf) {
Module["HEAPF64"] = HEAPF64 = new Float64Array(buf);
}
-var DYNAMIC_BASE = 6638304, DYNAMICTOP_PTR = 1395264;
+var DYNAMIC_BASE = 6635360, DYNAMICTOP_PTR = 1392320;
var INITIAL_INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216;
@@ -5739,9 +5739,9 @@ function _fd_write(fd, iov, iovcnt, pnum) {
}
}
-var ___tm_current = 1395280;
+var ___tm_current = 1392336;
-var ___tm_timezone = (stringToUTF8("GMT", 1395328, 4), 1395328);
+var ___tm_timezone = (stringToUTF8("GMT", 1392384, 4), 1392384);
function _gmtime_r(time, tmPtr) {
var date = new Date(HEAP32[time >> 2] * 1e3);
diff --git a/dist/dbr-9.6.32.wasm b/dist/dbr-9.6.42.wasm
similarity index 60%
rename from dist/dbr-9.6.32.wasm
rename to dist/dbr-9.6.42.wasm
index 3d2b76c..5730170 100644
Binary files a/dist/dbr-9.6.32.wasm and b/dist/dbr-9.6.42.wasm differ
diff --git a/dist/dbr-9.6.32.wasm.js b/dist/dbr-9.6.42.wasm.js
similarity index 100%
rename from dist/dbr-9.6.32.wasm.js
rename to dist/dbr-9.6.42.wasm.js
diff --git a/dist/dbr.d.ts b/dist/dbr.d.ts
new file mode 100644
index 0000000..c6dc389
--- /dev/null
+++ b/dist/dbr.d.ts
@@ -0,0 +1,2473 @@
+import { CameraEnhancer, DCEFrame } from 'dynamsoft-camera-enhancer';
+import { Howl } from 'dm-howler';
+
+declare enum EnumResultCoordinateType {
+ RCT_PIXEL = 1,
+ RCT_PERCENTAGE = 2
+}
+
+interface LocalizationResult {
+ /**
+ * The angle of a barcode. Values range from 0 to 360.
+ */
+ angle: number;
+ /**
+ * The X coordinate of the left-most point.
+ */
+ x1: number;
+ /**
+ * The X coordinate of the second point in a clockwise direction.
+ */
+ x2: number;
+ /**
+ * The X coordinate of the third point in a clockwise direction.
+ */
+ x3: number;
+ /**
+ * The X coordinate of the fourth point in a clockwise direction.
+ */
+ x4: number;
+ /**
+ * The Y coordinate of the left-most point.
+ */
+ y1: number;
+ /**
+ * The Y coordinate of the second point in a clockwise direction.
+ */
+ y2: number;
+ /**
+ * The Y coordinate of the third point in a clockwise direction.
+ */
+ y3: number;
+ /**
+ * The Y coordinate of the fourth point in a clockwise direction.
+ */
+ y4: number;
+ resultCoordinateType: EnumResultCoordinateType;
+ transformationMatrix: Array;
+}
+
+declare enum EnumBarcodeFormat {
+ BF_ALL = -29360129,
+ BF_ONED = 3147775,
+ BF_GS1_DATABAR = 260096,
+ BF_CODE_39 = 1,
+ BF_CODE_128 = 2,
+ BF_CODE_93 = 4,
+ BF_CODABAR = 8,
+ BF_ITF = 16,
+ BF_EAN_13 = 32,
+ BF_EAN_8 = 64,
+ BF_UPC_A = 128,
+ BF_UPC_E = 256,
+ BF_INDUSTRIAL_25 = 512,
+ BF_CODE_39_EXTENDED = 1024,
+ BF_GS1_DATABAR_OMNIDIRECTIONAL = 2048,
+ BF_GS1_DATABAR_TRUNCATED = 4096,
+ BF_GS1_DATABAR_STACKED = 8192,
+ BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL = 16384,
+ BF_GS1_DATABAR_EXPANDED = 32768,
+ BF_GS1_DATABAR_EXPANDED_STACKED = 65536,
+ BF_GS1_DATABAR_LIMITED = 131072,
+ BF_PATCHCODE = 262144,
+ BF_PDF417 = 33554432,
+ BF_QR_CODE = 67108864,
+ BF_DATAMATRIX = 134217728,
+ BF_AZTEC = 268435456,
+ BF_MAXICODE = 536870912,
+ BF_MICRO_QR = 1073741824,
+ BF_MICRO_PDF417 = 524288,
+ BF_GS1_COMPOSITE = -2147483648,
+ BF_MSI_CODE = 1048576,
+ BF_CODE_11 = 2097152,
+ BF_NULL = 0
+}
+
+/**
+ * @see [C++ TextResult](https://www.dynamsoft.com/barcode-reader/programming/c-cplusplus/struct/TextResult.html?src=cpp&&ver=latest)
+*/
+interface TextResult {
+ /**
+ * The barcode text.
+ */
+ barcodeText: string;
+ /**
+ * The barcode format.
+ */
+ barcodeFormat: number | EnumBarcodeFormat;
+ /**
+ * Barcode type in string.
+ */
+ barcodeFormatString: string;
+ /**
+ * The barcode content in a byte array.
+ */
+ barcodeBytes: number[];
+ /**
+ * The corresponding localization result.
+ */
+ localizationResult: LocalizationResult;
+}
+
+interface Region {
+ regionBottom: number;
+ regionRight: number;
+ regionLeft: number;
+ regionTop: number;
+ regionMeasuredByPercentage: number | boolean;
+}
+
+declare enum EnumIntermediateResultType {
+ IRT_NO_RESULT = 0,
+ IRT_ORIGINAL_IMAGE = 1,
+ IRT_COLOUR_CLUSTERED_IMAGE = 2,
+ IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE = 4,
+ IRT_TRANSFORMED_GRAYSCALE_IMAGE = 8,
+ IRT_PREDETECTED_REGION = 16,
+ IRT_PREPROCESSED_IMAGE = 32,
+ IRT_BINARIZED_IMAGE = 64,
+ IRT_TEXT_ZONE = 128,
+ IRT_CONTOUR = 256,
+ IRT_LINE_SEGMENT = 512,
+ IRT_FORM = 1024,
+ IRT_SEGMENTATION_BLOCK = 2048,
+ IRT_TYPED_BARCODE_ZONE = 4096,
+ IRT_PREDETECTED_QUADRILATERAL = 8192
+}
+
+declare enum EnumTerminatePhase {
+ TP_REGION_PREDETECTED = 1,
+ TP_IMAGE_PREPROCESSED = 2,
+ TP_IMAGE_BINARIZED = 4,
+ TP_BARCODE_LOCALIZED = 8,
+ TP_BARCODE_TYPE_DETERMINED = 16,
+ TP_BARCODE_RECOGNIZED = 32
+}
+
+declare enum EnumTextResultOrderMode {
+ TROM_CONFIDENCE = 1,
+ TROM_POSITION = 2,
+ TROM_FORMAT = 4,
+ TROM_SKIP = 0,
+ TROM_REV = 2147483648
+}
+
+declare enum EnumBinarizationMode {
+ BM_AUTO = 1,
+ BM_LOCAL_BLOCK = 2,
+ BM_SKIP = 0,
+ BM_THRESHOLD = 4,
+ BM_REV = 2147483648
+}
+
+declare enum EnumScaleUpMode {
+ SUM_AUTO = 1,
+ SUM_LINEAR_INTERPOLATION = 2,
+ SUM_NEAREST_NEIGHBOUR_INTERPOLATION = 4,
+ SUM_SKIP = 0,
+ SUM_REV = 2147483648
+}
+
+declare enum EnumLocalizationMode {
+ LM_SKIP = 0,
+ LM_AUTO = 1,
+ LM_CONNECTED_BLOCKS = 2,
+ LM_LINES = 8,
+ LM_STATISTICS = 4,
+ LM_SCAN_DIRECTLY = 16,
+ LM_STATISTICS_MARKS = 32,
+ LM_STATISTICS_POSTAL_CODE = 64,
+ LM_CENTRE = 128,
+ LM_ONED_FAST_SCAN = 256,
+ LM_REV = 2147483648
+}
+
+declare enum EnumBarcodeFormat_2 {
+ BF2_NULL = 0,
+ BF2_POSTALCODE = 32505856,
+ BF2_NONSTANDARD_BARCODE = 1,
+ BF2_USPSINTELLIGENTMAIL = 1048576,
+ BF2_POSTNET = 2097152,
+ BF2_PLANET = 4194304,
+ BF2_AUSTRALIANPOST = 8388608,
+ BF2_RM4SCC = 16777216,
+ BF2_DOTCODE = 2,
+ BF2_PHARMACODE_ONE_TRACK = 4,
+ BF2_PHARMACODE_TWO_TRACK = 8,
+ BF2_PHARMACODE = 12,
+ BF2_ALL = -1
+}
+
+/**
+ * @see [C++ RuntimeSettings](https://www.dynamsoft.com/barcode-reader/programming/c-cplusplus/struct/PublicRuntimeSettings.html?src=cpp&&ver=latest)
+ */
+interface RuntimeSettings {
+ /**
+ * Sets the formats of the barcode in BarcodeFormat group 1 to be read. Barcode formats in BarcodeFormat group 1 can be combined.
+ * ```js
+ * let runtimeSettings = await reader.getRuntimeSettings();
+ * runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE;
+ * await reader.updateRuntimeSettings(runtimeSettings);
+ * ```
+ */
+ barcodeFormatIds: number | EnumBarcodeFormat;
+ /**
+ * Sets the formats of the barcode in BarcodeFormat group 2 to be read. Barcode formats in BarcodeFormat group 1 can be combined.
+ */
+ barcodeFormatIds_2: number | EnumBarcodeFormat_2;
+ /**
+ * Sets the mode and priority for binarization.
+ */
+ binarizationModes: EnumBinarizationMode[];
+ /**
+ * Sets the degree of blurriness of the barcode.
+ */
+ deblurLevel: number;
+ /**
+ * Sets the number of barcodes expected to be detected for each image.
+ */
+ expectedBarcodesCount: number;
+ /**
+ * Sets the further modes.
+ */
+ furtherModes: any;
+ /**
+ * Sets which types of intermediate result to be kept for further reference. Intermediate result types can be combined.
+ */
+ intermediateResultTypes: EnumIntermediateResultType;
+ /**
+ * Sets the mode and priority for localization algorithms.
+ */
+ localizationModes: number[] | EnumLocalizationMode[];
+ /**
+ * Sets the range of barcode text length for barcodes search
+ */
+ minBarcodeTextLength: number;
+ /**
+ * The minimum confidence of the result
+ */
+ minResultConfidence: number;
+ /**
+ * Sets the region definition including the regionTop, regionLeft, regionRight, regionBottom and regionMeasuredByPercentage.
+ *
+ * Experimental feature:
+ *
+ * In [BarcodeScanner](../BarcodeScanner.md), `region` can be an array. For example `region = [r0, r1, r2]`, 0th frame use `r0`, 1st use `r1`, 2nd use `r2`, 3rd use `r0`, and then loop like this.
+ */
+ region: Region;
+ /**
+ * Specifies the format for the coordinates returned
+ */
+ resultCoordinateType: number | EnumResultCoordinateType;
+ /**
+ * Sets whether or not to return the clarity of the barcode zone.
+ */
+ returnBarcodeZoneClarity: number;
+ /**
+ * Sets the threshold for the image shrinking
+ */
+ scaleDownThreshold: number;
+ /**
+ * Sets the mode and priority to control the sampling methods of scale-up for linear barcode with small module sizes.
+ */
+ scaleUpModes: EnumScaleUpMode[];
+ /**
+ * Sets the phase where the algorithm stops.
+ */
+ terminatePhase: EnumTerminatePhase;
+ /**
+ * Sets the mode and priority for the order of the text results returned.
+ */
+ textResultOrderModes: EnumTextResultOrderMode[];
+ /**
+ * Sets the maximum amount of time (in milliseconds) that should be spent searching for a barcode per page.
+ * It does not include the time taken to load/decode an image (Tiff, PNG, etc) from disk into memory.
+ */
+ timeout: number;
+}
+
+declare enum EnumImagePixelFormat {
+ IPF_Binary = 0,
+ IPF_BinaryInverted = 1,
+ IPF_GrayScaled = 2,
+ IPF_NV21 = 3,
+ IPF_RGB_565 = 4,
+ IPF_RGB_555 = 5,
+ IPF_RGB_888 = 6,
+ IPF_ARGB_8888 = 7,
+ IPF_RGB_161616 = 8,
+ IPF_ARGB_16161616 = 9,
+ IPF_ABGR_8888 = 10,
+ IPF_ABGR_16161616 = 11,
+ IPF_BGR_888 = 12
+}
+
+declare enum EnumErrorCode {
+ DBR_SYSTEM_EXCEPTION = 1,
+ DBR_SUCCESS = 0,
+ DBR_UNKNOWN = -10000,
+ DBR_NO_MEMORY = -10001,
+ DBR_NULL_REFERENCE = -10002,
+ DBR_LICENSE_INVALID = -10003,
+ DBR_LICENSE_EXPIRED = -10004,
+ DBR_FILE_NOT_FOUND = -10005,
+ DBR_FILETYPE_NOT_SUPPORTED = -10006,
+ DBR_BPP_NOT_SUPPORTED = -10007,
+ DBR_INDEX_INVALID = -10008,
+ DBR_BARCODE_FORMAT_INVALID = -10009,
+ DBR_CUSTOM_REGION_INVALID = -10010,
+ DBR_MAX_BARCODE_NUMBER_INVALID = -10011,
+ DBR_IMAGE_READ_FAILED = -10012,
+ DBR_TIFF_READ_FAILED = -10013,
+ DBR_QR_LICENSE_INVALID = -10016,
+ DBR_1D_LICENSE_INVALID = -10017,
+ DBR_DIB_BUFFER_INVALID = -10018,
+ DBR_PDF417_LICENSE_INVALID = -10019,
+ DBR_DATAMATRIX_LICENSE_INVALID = -10020,
+ DBR_PDF_READ_FAILED = -10021,
+ DBR_PDF_DLL_MISSING = -10022,
+ DBR_PAGE_NUMBER_INVALID = -10023,
+ DBR_CUSTOM_SIZE_INVALID = -10024,
+ DBR_CUSTOM_MODULESIZE_INVALID = -10025,
+ DBR_RECOGNITION_TIMEOUT = -10026,
+ DBR_JSON_PARSE_FAILED = -10030,
+ DBR_JSON_TYPE_INVALID = -10031,
+ DBR_JSON_KEY_INVALID = -10032,
+ DBR_JSON_VALUE_INVALID = -10033,
+ DBR_JSON_NAME_KEY_MISSING = -10034,
+ DBR_JSON_NAME_VALUE_DUPLICATED = -10035,
+ DBR_TEMPLATE_NAME_INVALID = -10036,
+ DBR_JSON_NAME_REFERENCE_INVALID = -10037,
+ DBR_PARAMETER_VALUE_INVALID = -10038,
+ DBR_DOMAIN_NOT_MATCHED = -10039,
+ DBR_RESERVEDINFO_NOT_MATCHED = -10040,
+ DBR_AZTEC_LICENSE_INVALID = -10041,
+ DBR_LICENSE_DLL_MISSING = -10042,
+ DBR_LICENSEKEY_NOT_MATCHED = -10043,
+ DBR_REQUESTED_FAILED = -10044,
+ DBR_LICENSE_INIT_FAILED = -10045,
+ DBR_PATCHCODE_LICENSE_INVALID = -10046,
+ DBR_POSTALCODE_LICENSE_INVALID = -10047,
+ DBR_DPM_LICENSE_INVALID = -10048,
+ DBR_FRAME_DECODING_THREAD_EXISTS = -10049,
+ DBR_STOP_DECODING_THREAD_FAILED = -10050,
+ DBR_SET_MODE_ARGUMENT_ERROR = -10051,
+ DBR_LICENSE_CONTENT_INVALID = -10052,
+ DBR_LICENSE_KEY_INVALID = -10053,
+ DBR_LICENSE_DEVICE_RUNS_OUT = -10054,
+ DBR_GET_MODE_ARGUMENT_ERROR = -10055,
+ DBR_IRT_LICENSE_INVALID = -10056,
+ DBR_MAXICODE_LICENSE_INVALID = -10057,
+ DBR_GS1_DATABAR_LICENSE_INVALID = -10058,
+ DBR_GS1_COMPOSITE_LICENSE_INVALID = -10059,
+ DBR_PANORAMA_LICENSE_INVALID = -10060,
+ DBR_DOTCODE_LICENSE_INVALID = -10061,
+ DBR_PHARMACODE_LICENSE_INVALID = -10062,
+ DBR_IMAGE_ORIENTATION_INVALID = -10063,
+ DMERR_NO_LICENSE = -20000,
+ DMERR_LICENSE_SYNC_FAILED = -20003,
+ DMERR_TRIAL_LICENSE = -20010,
+ DMERR_FAILED_TO_REACH_LTS = -20200
+}
+
+interface BarcodeReaderException extends Error {
+ code?: EnumErrorCode;
+}
+
+interface DSImage {
+ data: Uint8Array;
+ width: number;
+ height: number;
+ pixelFormat: string;
+}
+
+interface ImageSource {
+ getImage(): Promise | DSImage;
+}
+
+/**
+ * let scanSettings = await scanner.getScanSettings();
+ * scanSettings.intervalTime = 100; // 100ms
+ * scanSettings.duplicateForgetTime = 3000; // 3s
+ * await scanner.updateScanSettings(scanSettings);
+ */
+interface ScanSettings {
+ intervalTime?: number;
+ duplicateForgetTime?: number;
+ oneDRememberFrameCount?: number;
+ oneDTrustFrameCount?: number;
+ /**
+ * Whether to play sound when the scanner reads a barcode successfully.
+ * Default value is `never`, which does not play sound.
+ * Use `frame` to play a sound when any barcode is found within a frame.
+ * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame.
+ * ```js
+ * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies
+ * startPlayButton.addEventListener('click', function() {
+ * scanner.whenToPlaySoundforSuccessfulRead = 'frame';
+ * });
+ * ```
+ * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2
+ */
+ whenToPlaySoundforSuccessfulRead?: string;
+ /**
+ * The sound to play when the scanner get successfull read.
+ * ```js
+ * scanner.soundOnSuccessfullRead = new Audio("./pi.mp3");
+ * ```
+ */
+ soundOnSuccessfullRead?: string;
+ /**
+ * Whether to vibrate when the scanner reads a barcode successfully.
+ * Default value is `never`, which does not vibrate.
+ * Use `frame` to vibrate when any barcode is found within a frame.
+ * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame.
+ * ```js
+ * // Can I use? https://caniuse.com/?search=vibrate
+ * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies
+ * startPlayButton.addEventListener('click', function() {
+ * scanner.whenToVibrateforSuccessfulRead = 'frame';
+ * });
+ * ```
+ */
+ whenToVibrateforSuccessfulRead?: string;
+ /**
+ * Get or set how long (ms) the vibration lasts.
+ * @see [[whenToVibrateforSuccessfulRead]]
+ */
+ vibrateDuration?: number;
+ captureAndDecodeInParallel?: boolean;
+ autoZoom?: boolean;
+ autoFocus?: boolean;
+ autoSuggestTip?: boolean;
+}
+
+interface ScannerPlayCallbackInfo {
+ height: number;
+ width: number;
+ deviceId: string;
+}
+
+interface Warning {
+ id: number;
+ message: string;
+}
+
+/**
+ * The `BarcodeReader` class is used for image decoding
+ * Comparing to `BarcodeScanner`, the default decoding settings are more accurate but slower.
+ * @example
+ * ```js
+ * (async()=>{
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * let results = await reader.decode(imageSource);
+ * for(let result of results){
+ * console.log(result.barcodeText);
+ * }
+ * })();
+ * ```
+ */
+declare class BarcodeReader {
+ private static _jsVersion;
+ private static _jsEditVersion;
+ protected static _version: string;
+ /**
+ * Returns the version of the library including the detailed version numbers of the engine and the main JavaScript code.
+ *
+ * The engine version is only valid after {@link loadWasm} has been called.
+ * @readonly
+ */
+ static get version(): string;
+ protected static _license: string;
+ /**
+ * Specify an online license or an offline license. Dynamsoft usually provides an online license.
+ *
+ * `license` needs to be set before {@link createInstance} or {@link loadWasm}.
+ *
+ * Besides, it is also recommended to set license in `data-license` attribute of `script` tag, instead of in `Javascript` code.
+ * @example
+ * ```html
+ *
+ * ```
+ * or
+ * ```js
+ * Dynamsoft.DBR.BarcodeReader.license = "YOUR-LICENSE-KEY";
+ * ```
+ */
+ static get license(): string;
+ static set license(license: string);
+ /** @ignore */
+ static get productKeys(): string;
+ /** @ignore */
+ static set productKeys(keys: string);
+ /** @ignore */
+ static get handshakeCode(): string;
+ /** @ignore */
+ static set handshakeCode(keys: string);
+ /** @ignore */
+ static get organizationID(): string;
+ /** @ignore */
+ static set organizationID(keys: string);
+ protected static _sessionPassword: string;
+ /** @ignore */
+ static set sessionPassword(value: string);
+ static get sessionPassword(): string;
+ /**
+ * @ignore
+ */
+ static browserInfo: {
+ browser: string;
+ version: number;
+ OS: string;
+ };
+ /**
+ * Detects the current running environment and returns a report.
+ * @returns A promise resolving to an object which contains some information of the current running environment.
+ * @example
+ * ```js
+ * console.log(await Dynamsoft.DBR.BarcodeReader.detectEnvironment());
+ * // {"wasm":true, "worker":true, "getUserMedia":true, "camera":true, "browser":"Chrome", "version":90, "OS":"Windows"}
+ * ```
+ */
+ static detectEnvironment(): Promise;
+ /** @ignore */
+ static _workerName: string;
+ protected static _engineResourcePath?: string;
+ static get engineResourcePath(): string;
+ /**
+ * Specify the Barcode Reader SDK engine (WASM) url. The SDK tries to automatically explore the engine location.
+ * If the auto-explored engine location is incorrect, you can manually specify the engine location.
+ * The property needs to be set before [[loadWasm]].
+ * ```js
+ * Dynamsoft.DBR.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode/dist/";
+ * await Dynamsoft.DBR.BarcodeReader.loadWasm();
+ * ```
+ */
+ static set engineResourcePath(value: string);
+ /** @ignore */
+ protected static _licenseServer?: string[];
+ static get licenseServer(): string[] | string;
+ /**
+ * Specify the license server URL.
+ */
+ static set licenseServer(value: string[] | string);
+ private static _deviceFriendlyName;
+ /**
+ * Sets a human-readable name that identifies the device.
+ * This name will appear in the device details table when you check the statistics of the according license.
+ * @defaultValue `""`
+ */
+ static get deviceFriendlyName(): string;
+ /** @ignore */
+ static set deviceFriendlyName(value: string);
+ static authCacheVersion: string;
+ /** @ignore */
+ static _isShowRelDecodeTimeInResults: boolean;
+ /** @ignore */
+ static _onLog: any;
+ /** @ignore */
+ static _bWasmDebug: boolean;
+ /** @ignore */
+ static _bNeverShowDialog: boolean;
+ /**
+ * Whether to use full feature wasm. The api may change in later version.
+ * For web, `_bUseFullFeature` is false as default.
+ * For Node.js, `_bUseFullFeature` will not work, and BarcodeReader will always work on full feature.
+ * The property needs to be set before `loadWasm`.
+ *
+ * Compact wasm:
+ * oned + qr + pdf417 + datamatrix.
+ * ===
+ * Full wasm:
+ * all supported barcode format +
+ * high level deblur available (lv8, 9) +
+ * DPM +
+ * template API +
+ * intermediate results API
+ * ===
+ * e.g.:
+ * Use compact in video deocode (small, download and initialization fast).
+ * Use full in file decode (need high level deblur).
+ *
+ *
+ * ```js
+ * DBR.BarcodeReader._bUseFullFeature = true;
+ * await DBR.BarcodeReader.loadWasm();
+ * ```
+ */
+ protected static __bUseFullFeature: boolean;
+ static get _bUseFullFeature(): boolean;
+ static set _bUseFullFeature(value: boolean);
+ /** @ignore */
+ static _dbrWorker: Worker;
+ protected static _nextTaskID: number;
+ protected static _taskCallbackMap: Map void>;
+ private static _pLoad;
+ /** @ignore */
+ static isImageSource(value: any): boolean;
+ /** @ignore */
+ static isDSImage(value: any): boolean;
+ /** @ignore */
+ static isDCEFrame(value: any): boolean;
+ /** @ignore */
+ _instanceID: number;
+ protected _ifSaveOriginalImageInACanvas: boolean;
+ /**
+ * Whether to save the original image into a `HTMLCanvasElement` element. The original image refers to the actual image the library tried to read barcodes from. It can be returned by {@link getOriginalImageInACanvas}.
+ * @defaultValue `false`
+ * @example
+ * ```js
+ * reader.ifSaveOriginalImageInACanvas = true;
+ * let results = await reader.decode(source);
+ * document.body.append(reader.getOriginalImageInACanvas());
+ * ```
+ * @see {@link getOriginalImageInACanvas}
+ */
+ get ifSaveOriginalImageInACanvas(): boolean;
+ set ifSaveOriginalImageInACanvas(value: boolean);
+ /** @ignore */
+ protected oriCanvas?: HTMLCanvasElement;
+ /** @ignore */
+ protected oriCanvasData?: any;
+ /**
+ * An `HTMLCanvasElement` that holds the original image.
+ * The original image refers to the actual image the library tried to read barcodes from.
+ * ```js
+ * reader.ifSaveOriginalImageInACanvas = true;
+ * let results = await reader.decode(source);
+ * document.body.append(reader.getOriginalImageInACanvas());
+ * ```
+ * @see {@link ifSaveOriginalImageInACanvas}
+ */
+ getOriginalImageInACanvas(): any;
+ /** @ignore */
+ private canvas;
+ protected bFilterRegionInJs: boolean;
+ protected userDefinedRegion: any;
+ protected _region?: Region | Region[];
+ protected set region(value: null | Region | Region[]);
+ protected get region(): null | Region | Region[];
+ /** @ignore */
+ _timeStartDecode: any;
+ /** @ignore */
+ _timeEnterInnerDBR: any;
+ /** @ignore */
+ _timeGetMessage: any;
+ /** @ignore */
+ decodeRecords: any;
+ /**
+ * @ignore A callback when wasm download success in browser environment.
+ */
+ static _onWasmDownloaded: () => void;
+ /**
+ * Check if the decoding module is loaded.
+ * @category Initialize and Destroy
+ */
+ static isWasmLoaded(): boolean;
+ protected bDestroyed: boolean;
+ /**
+ * Returns whether the instance has been destroyed.
+ * @see {@link destroyContext}
+ */
+ isContextDestroyed(): boolean;
+ /** @ignore */
+ protected static _lastErrorCode: number;
+ /** @ignore */
+ static get lastErrorCode(): number;
+ /** @ignore */
+ protected static _lastErrorString: string;
+ /** @ignore */
+ static get lastErrorString(): string;
+ /** @ignore */
+ protected static _setWarnnedEx: Set;
+ /** @ignore */
+ protected _lastErrorCode: number;
+ /** @ignore */
+ get lastErrorCode(): number;
+ /** @ignore */
+ protected _lastErrorString: string;
+ /** @ignore */
+ get lastErrorString(): string;
+ /** @ignore */
+ _lastInnerDecodeDuration: number;
+ private static _defaultUIElementURL;
+ /**
+ * Returns or sets the URL of the *.html* file that defines the default UI Element.
+ * The URL can only be set before the {@link createInstance} is called.
+ */
+ static get defaultUIElementURL(): string;
+ static set defaultUIElementURL(value: string);
+ /**
+ * A callback which is triggered when the running environment is not ideal. In this version, it may get triggered in two scenarios:
+ *
+ * 1. If the page is opened from the disk
+ * 2. The page is hosted in a HTTP site without SSL
+ *
+ * In both cases, the following warning is returned:
+ * ```js
+ * {
+ * id: 2,
+ * message: "Not connected via SSL (HTTPS), the SDK may not work correctly."
+ * }
+ * ```
+ * @defaultValue `undefined`
+ * @see {@link Warning}
+ */
+ static onWarning: (warning: Warning) => void;
+ protected static _fireHTTPSWarnning(): void;
+ /** @ignore */
+ intervalTime: number;
+ /** @ignore */
+ protected _intervalGetVideoFrame: number;
+ protected _loopReadVideoTimeoutId: any;
+ /** @ignore */
+ protected array_getFrameTimeCost: any[];
+ /** @ignore */
+ protected array_decodeFrameTimeCost: any[];
+ /** @ignore */
+ protected _indexCurrentDecodingFrame: number;
+ protected _dbrDrawingLayer: any;
+ protected _arrPolygons: any;
+ protected _bPauseScan: boolean;
+ protected _intervalDetectVideoPause: number;
+ /** @ignore */
+ beepSound: Howl;
+ private _soundSource;
+ private get soundSource();
+ private set soundSource(value);
+ /**
+ * Whether to play sound when the scanner reads a barcode successfully.
+ * Default value is `false`, which does not play sound.
+ * Use `frame` or `true` to play a sound when any barcode is found within a frame.
+ * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame.
+ * ```js
+ * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies
+ * startPlayButton.addEventListener('click', function() {
+ * scanner.bPlaySoundOnSuccessfulRead = true;
+ * });
+ * ```
+ * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2
+ * @ignore
+ */
+ protected bPlaySoundOnSuccessfulRead: (boolean | string);
+ private get whenToPlaySoundforSuccessfulRead();
+ /**
+ * Whether to play sound when the scanner reads a barcode successfully.
+ * Default value is `never`, which does not play sound.
+ * Use `frame` to play a sound when any barcode is found within a frame.
+ * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame.
+ * ```js
+ * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies
+ * startPlayButton.addEventListener('click', function() {
+ * scanner.whenToPlaySoundforSuccessfulRead = 'frame';
+ * });
+ * ```
+ * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2
+ * @ignore
+ */
+ private set whenToPlaySoundforSuccessfulRead(value);
+ /**
+ * Whether to vibrate when the scanner reads a barcode successfully.
+ * Default value is `false`, which does not vibrate.
+ * Use `frame` or `true` to vibrate when any barcode is found within a frame.
+ * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame.
+ * ```js
+ * // Can I use? https://caniuse.com/?search=vibrate
+ * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies
+ * startVibrateButton.addEventListener('click', function() {
+ * scanner.bVibrateOnSuccessfulRead = true;
+ * });
+ * ```
+ * @ignore
+ */
+ protected bVibrateOnSuccessfulRead: (boolean | string);
+ /**
+ * Get or set how long (ms) the vibration lasts.
+ * @see [[whenToVibrateforSuccessfulRead]]
+ * @ignore
+ */
+ protected vibrateDuration: number;
+ private get whenToVibrateforSuccessfulRead();
+ /**
+ * Whether to vibrate when the scanner reads a barcode successfully.
+ * Default value is `never`, which does not vibrate.
+ * Use `frame` to vibrate when any barcode is found within a frame.
+ * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame.
+ * ```js
+ * // Can I use? https://caniuse.com/?search=vibrate
+ * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies
+ * startPlayButton.addEventListener('click', function() {
+ * scanner.whenToVibrateforSuccessfulRead = 'frame';
+ * });
+ * ```
+ * @ignore
+ */
+ private set whenToVibrateforSuccessfulRead(value);
+ protected captureAndDecodeInParallel: boolean;
+ protected autoSuggestTip: boolean;
+ protected suggestTipFrameArray: Array;
+ protected suggestTipFrameLimit: number[];
+ protected noIntermediateResultsCount: number;
+ protected noIntermediateResultsTipLimit: number;
+ protected tinyBarcodeTipModuleSizeLimit: number;
+ protected hugeBarcodeTipLimit: number;
+ protected autoZoomInFrameArray: Array;
+ protected autoZoomInFrameLimit: number[];
+ protected autoZoomInStepRate: number;
+ protected autoZoomInMaxStep: number;
+ protected autoZoomInMaxTimes: number;
+ protected autoZoomInMinStep: number;
+ protected autoZoomInIdealModuleSize: number;
+ protected autoZoomOutFrameCount: number;
+ protected autoZoomOutFrameLimit: number;
+ protected autoZoomOutStepRate: number;
+ protected autoZoomOutMinValue: number;
+ protected autoZoomOutMinStep: number;
+ protected autoZoomOutStepRate_2: number;
+ protected autoZoomOutMinValue_2: number;
+ protected frameArrayInIdealZoom: Array;
+ protected frameLimitInIdealZoom: number[];
+ protected enableZoomOutInIdealZoom: boolean;
+ protected nextActionInIdealZoom: string;
+ protected autoFocusFrameArray: Array;
+ protected autoFocusFrameLimit: number[];
+ protected autoZoomIdealArea: number[];
+ protected autoZoomTargetBorder: number;
+ protected autoZoomDetectionArea: number;
+ protected autoZoom: boolean;
+ protected autoFocus: boolean;
+ protected _clearResultsCanvasTimeoutId: any;
+ _resultHighlightingDuration: number;
+ private _dce;
+ protected set dce(value: CameraEnhancer);
+ protected get dce(): CameraEnhancer;
+ protected _drawingItemNamespace: any;
+ protected _styleIdBeforeVerification: number;
+ private _dceControler;
+ private _imgSource;
+ private callbackCameraChange?;
+ private callbackResolutionChange?;
+ private callbackCameraClose?;
+ private callbackSingleFrameAcquired?;
+ protected _maxCvsSideLength: number;
+ /** @ignore */
+ set maxCvsSideLength(value: number);
+ get maxCvsSideLength(): number;
+ private _registerDCEControler;
+ private _logoutDCEControler;
+ /**
+ * Sets an image source for continous scanning.
+ * @param imgSource Specifies the image source.
+ * @param options Options to help with the usage of the `ImageSource` object. At present, it only contains one property `resultsHighlightBaseShapes` that accepts `Dynamsoft.DCE.DrawingItem` as its value to help with the highlighting of barcode regions as shown in the code snippet below. More properties will be added as needed in the future.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance();
+ * let options = { resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem };
+ * await reader.setImageSource(enhancer, options);
+ * reader.onUniqueRead = (txt, result) => {
+ * console.log(txt);
+ * };
+ * await reader.startScanning(true);
+ * ```
+ * @see {@link ImageSource}
+ */
+ setImageSource(imgSource: ImageSource | CameraEnhancer, options?: any): Promise;
+ /**
+ * Downloads and compiles the engine to get it loaded/ready for a `BarcodeReader` or `BarcodeScanner` instance to be created.
+ * You can call this API to silently set the operating environment of the library as soon as the page is loaded, avoiding unnecessary waiting time when using the library later.
+ *
+ * If this API is not called beforehand, it will be called automatically when creating an instance of `BarcodeReader` or `BarcodeScanner`.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * window.addEventListener('DOMContentLoaded', (event) => {
+ * Dynamsoft.DBR.BarcodeReader.loadWasm();
+ * });
+ * ```
+ * @category Initialize and Destroy
+ */
+ static loadWasm(): Promise;
+ /**
+ * @param type "warn" or "error"
+ * @param content
+ * @returns
+ */
+ protected static showDialog(type: string, content: string): Promise;
+ protected static createInstanceInWorker(bScanner?: boolean): Promise;
+ protected constructor();
+ /**
+ * Creates a `BarcodeReader` instance.
+ * @returns A promise resolving to the created `BarcodeReader` object.
+ * @example
+ * ```
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * ```
+ * @see {@link destroyContext}
+ * @category Initialize and Destroy
+ */
+ static createInstance(): Promise;
+ protected clearMapDecodeRecord(): Promise;
+ /**
+ * Decode barcodes from a image.
+ * If the content in the binary data is raw img data, such as `RGBA` , use {@link decodeBuffer} instead.
+ *
+ * Note: To speed up the reading, the image will be scaled down when it exceeds a size limit either horizontally or vertically.
+ * The limit is 2048 pixels on mobile devices and 4096 on other devices.
+ * If the template "dense" or "distance" is used, the limit is 4096 regardless of which device is used.
+ * @param source specifies the image to decode. The supported image formats include `png` , `jpeg` , `bmp` , `gif` and a few others (some browsers support `webp` , `tif` ).
+ * Also note that the image can be specified in a lot of ways including binary data, base64 string (with MIME), URL, etc.
+ * @returns A promise resolving to an array of `TextResult` that contains all the barcode results found in this image.
+ * @example
+ * ```js
+ * let results1 = await reader.decode(blob);
+ * let results2 = await reader.decode(htmlImageElement);
+ * let results3 = await reader.decode(url);
+ * let results4 = await reader.decode(base64WithMime); // like `data:image/png;base64,iV************`
+ * ```
+ *
+ * You can even use an `HTMLVideoElement` as the source. If the video is playing, the current frame will be decoded.
+ *
+ * ```js
+ * let results;
+ * try{
+ * // The current frame will be decoded.
+ * results = await reader.decode(htmlVideoElement);
+ * }catch(ex){
+ * // If no frame in the video, will throw an exception.
+ * }
+ * ```
+ * @see {@link TextResult}
+ * @see {@link decodeBuffer}
+ * @category Decode
+ */
+ decode(source: Blob | ArrayBuffer | Uint8Array | Uint8ClampedArray | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | string | DCEFrame | DSImage): Promise;
+ /**
+ * Decodes barcodes from a base64-encoded image (with or without MIME).
+ * @param base64 Specifies the image represented by a string.
+ * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image.
+ * @example
+ * ```js
+ * let results = await reader.decodeBase64String(strBase64); //e.g. `data:image/jpg;base64,Xfjshekk....` or `Xfjshekk...`.
+ * for(let result of results){
+ * console.log(result.barcodeText);
+ * }
+ * ```
+ * @see {@link TextResult}
+ * @category Decode
+ */
+ decodeBase64String(base64: string): Promise;
+ /**
+ * Decodes barcodes from an image specified by its URL.
+ *
+ * Note that the image should either be from the same domain or has the 'Access-Control-Allow-Origin' header set to allow access from your current domain.
+ * @param url Specifies the image by its URL.
+ * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image.
+ * @example
+ * ```js
+ * let results = await reader.decodeUrl("https://www.yourdomain.com/imageWithBarcodes.png");
+ * for(let result of results){
+ * console.log(result.barcodeText);
+ * }
+ * ```
+ * @see {@link TextResult}
+ * @category Decode
+ */
+ decodeUrl(url: string): Promise;
+ /**
+ * Decodes barcodes from the memory buffer containing image pixels in defined format.
+ * @ignore
+ */
+ _decodeBuffer_Uint8Array(buffer: Uint8Array | Uint8ClampedArray, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise;
+ /**
+ *
+ * @param buffer
+ * @param width
+ * @param height
+ * @param stride
+ * @param format
+ * @param config
+ * @ignore
+ */
+ _decodeBuffer_Blob(buffer: Blob, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise;
+ /**
+ * Decodes barcodes from raw image data. It is an advanced API, if you don't know what you are doing, use [decode](#decode) instead.
+ * @param buffer Specifies the raw image represented by a `Uint8Array` , `Uint8ClampedArray` , `ArrayBuffer` or `Blob` object.
+ * @param width Image width.
+ * @param height Image height.
+ * @param stride `image-width * pixel-byte-length`.
+ * @param format Pixel format.
+ * @param config Specifies the oritation of the image data.
+ * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image.
+ * @example
+ * ```js
+ * let results = await reader.decodeBuffer(u8RawImage, 1280, 720, 1280 * 4, Dynamsoft.DBR.EnumImagePixelFormat.IPF_ABGR_8888);
+ * for (let result of results) {
+ * console.log(result.barcodeText);
+ * }
+ * ```
+ * @see {@link TextResult}
+ * @see {@link EnumImagePixelFormat}
+ * @category Decode
+ */
+ decodeBuffer(buffer: Uint8Array | Uint8ClampedArray | ArrayBuffer | Blob, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise;
+ /** @ignore */
+ _decodeFileInMemory_Uint8Array(bytes: Uint8Array): Promise;
+ /**
+ * Returns the current runtime settings.
+ * @returns A promise resolving to a {@link RuntimeSettings} object that contains the settings for barcode reading.
+ * @example
+ * ```js
+ * let settings = await reader.getRuntimeSettings();
+ * settings.deblurLevel = 5;
+ * await reader.updateRuntimeSettings(settings);
+ * ```
+ * @see {@link RuntimeSettings}
+ * @see {@link updateRuntimeSettings}
+ * @see {@link resetRuntimeSettings}
+ * @category Runtime Settings
+ */
+ getRuntimeSettings(): Promise;
+ /**
+ * Updates runtime settings.
+ * @param settings a {@link RuntimeSettings} object, or a string represent one of preset templates:
+ *
+ * `speed`: fast but may miss a few codes;
+ *
+ * `coverage`: slow but try to find all codes, this is the default setting for a `BarcodeReader` instance;
+ *
+ * `balance`: between `speed` and `coverage`;
+ *
+ * `dense`: optimized for scanning dense barcodes such as the PDF417 on driver's license;
+ *
+ * `distance`: optimized for scanning a barcode that is placed far from the device and appear small in the video stream.
+ *
+ * Note: If the settings `barcodeFormatIds` , `barcodeFormatIds_2` and `region` have been changed by the customer, changing the template will preserve the previous settings.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await reader.updateRuntimeSettings('balance');
+ * let settings = await reader.getRuntimeSettings();
+ * settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED;
+ * await reader.updateRuntimeSettings(settings);
+ * ```
+ * @see {@link RuntimeSettings}
+ * @see {@link getRuntimeSettings}
+ * @see {@link resetRuntimeSettings}
+ * @category Runtime Settings
+ */
+ updateRuntimeSettings(settings: RuntimeSettings | string): Promise;
+ /**
+ * Resets all parameters to default values.
+ *
+ * For a `BarcodeReader` instance, it is equivalent to setting the `coverage` template.
+ *
+ * For a `BarcodeScanner` instance, it is equivalent to setting the `single` template.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await reader.resetRuntimeSettings();
+ * ```
+ * @category Runtime Settings
+ */
+ resetRuntimeSettings(): Promise;
+ /**
+ *
+ * @returns
+ * @ignore
+ */
+ _resetRuntimeSettingsToCppDefault(): Promise;
+ /**
+ * Return the current `RuntimeSettings` in the form of a string.
+ * @returns A promise resolving to a string which represents the current `RuntimeSettings`.
+ * @example
+ * ```js
+ * let strSettings = await reader.outputRuntimeSettingsToString();
+ * ```
+ * @see {@link RuntimeSettings}
+ * @see {@link getRuntimeSettings}
+ * @category Runtime Settings
+ */
+ outputRuntimeSettingsToString(): Promise;
+ /**
+ * Initialize runtime settings with the settings in given JSON string.
+ * @param settings A string representing the template.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await reader.initRuntimeSettingsWithString("{\"Version\":\"3.0\", \"ImageParameter\":{\"Name\":\"IP1\", \"BarcodeFormatIds\":[\"BF_QR_CODE\"], \"ExpectedBarcodesCount\":10}}");
+ * ```
+ * @see {@link RuntimeSettings}
+ * @see {@link updateRuntimeSettings}
+ * @category Runtime Settings
+ */
+ initRuntimeSettingsWithString(settings: any): Promise;
+ private _decode_Blob;
+ /**
+ *
+ * @param arrayBuffer
+ * @param config
+ * @ignore
+ */
+ private _decode_ArrayBuffer;
+ /**
+ *
+ * @param uint8Array
+ * @param config
+ * @ignore
+ */
+ private _decode_Uint8Array;
+ /**
+ *
+ * @param image
+ * @param config
+ * @ignore
+ */
+ private _decode_Image;
+ private _decode_Canvas;
+ /**
+ * decode video is not multi call safe in an instance, we reuse many thing for speed, so make sure wait util one finish then call next
+ * @param video
+ * @param config
+ * @ignore
+ */
+ _decode_Video(video: HTMLVideoElement, config?: any): Promise;
+ /**@ignore */
+ _decode_DCEFrame(dceFrame: DCEFrame, config?: any): Promise;
+ /**@ignore */
+ _decode_DSImage(dsImage: DSImage, config?: any): Promise;
+ private _decode_Base64;
+ private _decode_Url;
+ /**
+ * The coordinates of results are related to the cropping image gotten from DCE JS. Transform it to the coordinates related to the whole video/image.
+ * @ignore
+ */
+ static recalculateResultLocation(results: Array<{
+ localizationResult: any;
+ }>, sx: number, sy: number, sWidth: number, sHeight: number, dWidth: number, dHeight: number): void;
+ /** @ignore */
+ static BarcodeReaderException(ag0: any, ag1: any): BarcodeReaderException;
+ protected _handleRetJsonString(objRet: any): any;
+ /**
+ * Sets the argument value for the specified mode parameter.
+ * @param modeName Specifies the mode which contains one or multiple elements.
+ * @param index Specifies an element of the mode by its index.
+ * @param argumentName Specifies the argument.
+ * @param argumentValue Specifies the value.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await reader.setModeArgument("BinarizationModes", 0, "EnableFillBinaryVacancy", "1");
+ * ```
+ * @see {@link getModeArgument}
+ * @category Runtime Settings
+ */
+ setModeArgument(modeName: string, index: number, argumentName: string, argumentValue: string): Promise;
+ /**
+ * Returns the argument value for the specified mode parameter.
+ * @param modeName Specifies the mode which contains one or multiple elements.
+ * @param index Specifies an element of the mode by its index.
+ * @param argumentName Specifies the argument.
+ * @returns A promise resolving to a string which represents the value of the argument.
+ * @example
+ * ```js
+ * let argumentValue = await reader.getModeArgument("BinarizationModes", 0, "EnableFillBinaryVacancy");
+ * ```
+ * @see {@link setModeArgument}
+ * @category Runtime Settings
+ */
+ getModeArgument(modeName: string, index: number, argumentName: string): Promise;
+ /**
+ * The method is only supported in the full feature edition.
+ * Returns intermediate results containing the original image, the colour clustered image, the binarized Image, contours, Lines, TextBlocks, etc.
+ * ```js
+ * let imResults = await reader.getIntermediateResults();
+ * ```
+ * @ignore
+ */
+ getIntermediateResults(): Promise;
+ /** @ignore */
+ getIntermediateCanvas(): Promise;
+ /**
+ * This event is triggered after the library finishes scanning a image.
+ * @event onImageRead
+ * @defaultValue `undefined`
+ * @param results An array of `TextResult` object that contains the barcode results in this frame.
+ * @example
+ * ```js
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance();
+ * let options = {
+ * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem
+ * };
+ * await reader.setImageSource(enhancer, options);
+ * reader.onImageRead = (results) => {
+ * if (results.length > 0) {
+ * results.forEach(result => {
+ * console.log(result.barcodeText);
+ * });
+ * }
+ * };
+ * await reader.startScanning(true);
+ * ```
+ * @see {@link TextResult}
+ * @see {@link onUniqueRead}
+ */
+ onImageRead?: (results: TextResult[]) => void;
+ /**
+ * This event is triggered when a new, unduplicated label is found.
+ * @event onUniqueRead
+ * @defaultValue `undefined`
+ * @param txt A string that holds the barcode text.
+ * @param txt A {@link TextResult} object that contains more detailed info.
+ * @example
+ * ```js
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance();
+ * let options = {
+ * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem
+ * };
+ * await reader.setImageSource(enhancer, options);
+ * reader.onUniqueRead = (txt, result) => {
+ * console.log(txt);
+ * };
+ * await reader.startScanning(true);
+ * ```
+ * @see {@link TextResult}
+ * @see {@link onImageRead}
+ */
+ onUniqueRead?: (txt: string, result: TextResult) => void;
+ /**
+ * Get current scan settings.
+ * @returns A promise resolving to a {@link ScanSettings}.
+ * @example
+ * ```js
+ * let scanSettings = await scanner.getScanSettings();
+ * scanSettings.intervalTime = 50;
+ * scanSettings.duplicateForgetTime = 1000;
+ * await scanner.updateScanSettings(scanSettings);
+ * ```
+ * @see {@link ScanSettings}
+ * @see {@link updateScanSettings}
+ */
+ getScanSettings(): Promise;
+ /**
+ * Changes scan settings with the object passed in.
+ * @param settings Specifies the new scan settings.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * let scanSettings = await scanner.getScanSettings();
+ * scanSettings.intervalTime = 50;
+ * scanSettings.duplicateForgetTime = 1000;
+ * await scanner.updateScanSettings(scanSettings);
+ * ```
+ * @see {@link ScanSettings}
+ * @see {@link getScanSettings}
+ */
+ updateScanSettings(settings: ScanSettings): Promise;
+ /** @ignore */
+ _cloneDecodeResults(results: any): any;
+ protected _loopReadVideo(): Promise;
+ /**
+ * start dce fetching frame loop, and get frame from frame queue
+ * @ignore
+ */
+ protected _getVideoFrame(): DCEFrame;
+ /**
+ * Add drawing items according to results, and add notes to drawing items.
+ * @param results
+ * @param notes
+ * @returns
+ * @ignore
+ */
+ protected _drawResults(results: Array<{
+ localizationResult: any;
+ resultState?: number;
+ }>, notes?: Array): void;
+ /**
+ * _promiseStartScan.status == "pending"; // camera is openning.
+ * _promiseStartScan.status == "fulfilled"; // camera is opened.
+ * _promiseStartScan == null; // camera is closed.
+ * @ignore
+ */
+ private _promiseStartScan;
+ /**
+ * Open the camera and starts continuous scanning of incoming images.
+ * @param appendOrShowUI this parameter specifies how to handle the UI that comes with the bound CameraEnhancer instance.
+ * When set to true, if the UI doesn't exist in the DOM tree, the `CameraEnhancer` instance will append it in the DOM and show it; if the UI already exists in the DOM tree but is hidden, it'll be displayed.
+ * When not set or set to false, it means not to change the original state of that UI: if it doesn't exist in the DOM tree, nothing shows up on the page; if it exists in the DOM tree, it may or may not show up depending on its original state.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object which contains the resolution of the video.
+ * @example
+ * ```js
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance();
+ * let options = {
+ * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem
+ * };
+ * await reader.setImageSource(enhancer, options);
+ * reader.onUniqueRead = (txt, result) => {
+ * console.log(txt);
+ * };
+ * await reader.startScanning(true);
+ * ```
+ * @see {@link ScannerPlayCallbackInfo}
+ * @see {@link stopScanning}
+ * @see {@link pauseScanning}
+ * @see {@link resumeScanning}
+ * @category Open and Close
+ */
+ startScanning(bShowUI?: boolean): Promise;
+ /**
+ * Stops continuous scanning and closes the video stream.
+ * @param hideUI this parameter specifies how to handle the UI that comes with the bound `CameraEnhancer` instance.
+ * When set to true, if the UI doesn't exist in the DOM tree or it exists but is hidden, nothing is done; if the UI already exists in the DOM tree and is shown, it'll be hidden.
+ * When not set or set to false, it means not to change the original state of that UI: if it doesn't exist in the DOM tree, nothing happens; if it exists in the DOM tree, it may or may not be hidden depending on its original state.
+ * @example
+ * ```js
+ * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance();
+ * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance();
+ * let options = {
+ * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem
+ * };
+ * await reader.setImageSource(enhancer, options);
+ * reader.onUniqueRead = (txt, result) => {
+ * console.log(txt);
+ * reader.stopScanning(true);
+ * };
+ * await reader.startScanning(true);
+ * ```
+ * @see {@link startScanning}
+ * @see {@link pauseScanning}
+ * @see {@link resumeScanning}
+ * @category Open and Close
+ */
+ stopScanning(bHideUI?: boolean): void;
+ /**
+ * Pause continuous scanning but keep the video stream.
+ * @param options Options to configure how the pause works.
+ * At present, it only contains one property `keepResultsHighlighted` which, when set to `true`, will keep the barcodes found on the frame (at the time of the pause) highlighted.
+ * @see {@link resumeScanning}
+ * @category Pause and Resume
+ */
+ pauseScanning(options?: any): void;
+ /**
+ * Resumes continuous scanning.
+ * @see {@link pauseScanning}
+ * @category Pause and Resume
+ */
+ resumeScanning(): void;
+ /**
+ * Destroy the `BarcodeReader` instance.
+ * If your page needs to create new instances from time to time, don't forget to destroy unused old instances.
+ * @see {@link isContextDestroyed}
+ * @category Initialize and Destroy
+ */
+ destroyContext(): void;
+}
+
+interface VideoDeviceInfo {
+ deviceId: string;
+ label: string;
+ /** @ignore */
+ _checked: boolean;
+}
+
+/**
+ * The `BarcodeScanner` class is used for video decoding.
+ * Its instance gets access to a camera via the 'MediaDevices' interface, then uses its built-in UI to show the camera input and perform continuous barcode scanning on the incoming frames.
+ * @example
+ * ```js
+ * let scanner;
+ * (async()=>{
+ * scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
+ * scanner.onUniqueRead = txt => console.log(txt);
+ * await scanner.show();
+ * })();
+ * ```
+ * @extends BarcodeReader
+ */
+declare class BarcodeScanner extends BarcodeReader {
+ #private;
+ /** @ignore */
+ static set _onLog(value: (message: any) => void);
+ static get _onLog(): (message: any) => void;
+ /**
+ * Returns the version of the library including the detailed version numbers of the engine and the main JavaScript code.
+ *
+ * The engine version is only valid after {@link loadWasm} has been called.
+ * @readonly
+ */
+ static get version(): string;
+ /**
+ * A callback which is triggered when the running environment is not ideal. In this version, it may get triggered in two scenarios:
+ *
+ * 1. If the page is opened from the disk
+ * 2. The page is hosted in a HTTP site without SSL
+ *
+ * In both cases, the following warning is returned:
+ * ```js
+ * {
+ * id: 2,
+ * message: "Not connected via SSL (HTTPS), the SDK may not work correctly."
+ * }
+ * ```
+ * @defaultValue `undefined`
+ * @see {@link Warning}
+ */
+ static onWarning: (warning: Warning) => void;
+ protected static _fireHTTPSWarnning(): void;
+ /**
+ * Test whether there is an available camera. It is also a trick to speed up the opening of the camera.
+ * @returns A promise resolving to a object contains the message.
+ */
+ static testCameraAccess(): Promise<{
+ ok: boolean;
+ message: string;
+ }>;
+ /**
+ * A callback which is triggered when the resolution is not ideal (< 720P).
+ * @defaultValue `undefined`
+ * @see {@link Warning}
+ */
+ onWarning: (warning: Warning) => void;
+ private _fireResolutionWarning;
+ /**
+ * Returns the HTML element that is used by the `BarcodeScanner` instance.
+ * @returns The HTML element that is used by the `BarcodeScanner` instance.
+ * @see {@link setUIElement}
+ * @category UI
+ */
+ getUIElement(): HTMLElement;
+ /**
+ * Specifies an HTML element for the `BarcodeScanner` instance to use as its UI. The structure inside the element determines the appearance of the UI.
+ * @param elementOrUrl specifies the element or the element url.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```html
+ *
+ *
+ * ```
+ * @see {@link getUIElement}
+ * @category UI
+ */
+ setUIElement(elementOrUrl: HTMLElement | string): Promise;
+ /**
+ * Returns or sets the status of single frame mode.
+ * If enabled, the video input will not be played and the user can choose to take a picture with the system camera (mobile only) or select an existing image from the photo library for barcode reading.
+ *
+ * Because the system camera of a mobile device can provide pictures with better quality, the API is useful when facing complex scenarios such as reading the dense PDF417 code on a driver license.
+ *
+ * The single-frame mode can only be enabled or disabled before the video input starts playing (before `scanner.show()` is called).
+ * @defaultValue In general, the default value is `false`. But if the browser does not support the `MediaDevices`/`getUserMedia`, it will be set as `true` automatically when {@link createInstance} is called.
+ * @example
+ * ```js
+ * let scanner;
+ * (async()=>{
+ * scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
+ * scanner.singleFrameMode = true;
+ * await scanner.show();
+ * })();
+ * ```
+ */
+ get singleFrameMode(): boolean | "image" | "camera";
+ set singleFrameMode(value: boolean | "image" | "camera");
+ /**
+ * Specifies an event handler which fires after the library finishes scanning a frame.
+ * @event onFrameRead
+ * @defaultValue `undefined`
+ * @param results An array of {@link TextResult} object that contains the barcode results in this frame.
+ * @example
+ * ```js
+ * scanner.onFrameRead = results => {
+ * for(let result of results){
+ * console.log(result.barcodeText);
+ * }
+ * };
+ * ```
+ * @see {@link TextResult}
+ * @see {@link onUniqueRead}
+ */
+ onFrameRead?: (results: TextResult[]) => void;
+ /**
+ * @deprecated Use {@link onUniqueRead} instead.
+ */
+ get onUnduplicatedRead(): (txt: string, result: TextResult) => void;
+ set onUnduplicatedRead(value: (txt: string, result: TextResult) => void);
+ /**
+ * Returns `HTMLVideoElement` element that the `BarcodeScanner` instance used.
+ * @readonly
+ */
+ get video(): HTMLVideoElement;
+ /**
+ * Sets or returns the source of the video.
+ * You can use this property to specify an existing video as the source to play which will be processed the same way as the video feed from a live camera.
+ * @defaultValue `null`
+ */
+ set videoSrc(source: string | MediaStream | MediaSource | Blob);
+ get videoSrc(): string | MediaStream | MediaSource | Blob;
+ /**
+ * Sets or returns the the maximum time allowed for opening a selected camera.
+ * @defaultValue `4000`
+ */
+ set cameraOpenTimeout(value: number);
+ get cameraOpenTimeout(): number;
+ /**
+ * An event that gets triggered whenever a 'Tip' is suggested.
+ * @event onTipSuggested
+ * @defaultValue `undefined`
+ * @param occasion Specifies the occasion for the Tip.
+ * @param message The 'Tip' message for the occasion.
+ * @see {@link showTip}
+ */
+ set onTipSuggested(value: (occasion: string, message: string) => void);
+ get onTipSuggested(): (occasion: string, message: string) => void;
+ private _assertOpen;
+ private _barcodeFillStyle;
+ /**
+ * Specifies the color used inside the shape which highlights a found barcode.
+ * @defaultValue `"rgba(254,180,32,0.3)"`
+ * @see {@link barcodeStrokeStyle}
+ * @see {@link barcodeLineWidth}
+ * @see {@link barcodeFillStyleBeforeVerification}
+ * @see {@link barcodeStrokeStyleBeforeVerification}
+ * @see {@link barcodeLineWidthBeforeVerification}
+ * @category UI
+ */
+ set barcodeFillStyle(style: string);
+ get barcodeFillStyle(): string;
+ private _barcodeStrokeStyle;
+ /**
+ * Specifies the color used to paint the outline of the shape which highlights a found barcode.
+ * @defaultValue `"rgba(254,180,32,0.9)"`
+ * @see {@link barcodeFillStyle}
+ * @see {@link barcodeLineWidth}
+ * @see {@link barcodeFillStyleBeforeVerification}
+ * @see {@link barcodeStrokeStyleBeforeVerification}
+ * @see {@link barcodeLineWidthBeforeVerification}
+ * @category UI
+ */
+ set barcodeStrokeStyle(style: string);
+ get barcodeStrokeStyle(): string;
+ private _barcodeLineWidth;
+ /**
+ * Specifies the line width of the outline of the shape which highlights a found barcode.
+ * @defaultValue `1`
+ * @see {@link barcodeFillStyle}
+ * @see {@link barcodeStrokeStyle}
+ * @see {@link barcodeFillStyleBeforeVerification}
+ * @see {@link barcodeStrokeStyleBeforeVerification}
+ * @see {@link barcodeLineWidthBeforeVerification}
+ * @category UI
+ */
+ set barcodeLineWidth(width: number);
+ get barcodeLineWidth(): number;
+ private _barcodeFillStyleBeforeVerification;
+ /**
+ * Specifies the color used inside the shape which highlights a found linear barcode which has not been verified.
+ * @defaultValue `"rgba(248,252,0,0.2)"`
+ * @see {@link barcodeStrokeStyleBeforeVerification}
+ * @see {@link barcodeLineWidthBeforeVerification}
+ * @see {@link barcodeFillStyle}
+ * @see {@link barcodeStrokeStyle}
+ * @see {@link barcodeLineWidth}
+ * @category UI
+ */
+ set barcodeFillStyleBeforeVerification(style: string);
+ get barcodeFillStyleBeforeVerification(): string;
+ private _barcodeStrokeStyleBeforeVerification;
+ /**
+ * Specifies the color used to paint the outline of the shape which highlights a found linear barcode which has not been verified.
+ * @defaultValue `"transparent"`
+ * @see {@link barcodeFillStyleBeforeVerification}
+ * @see {@link barcodeLineWidthBeforeVerification}
+ * @see {@link barcodeFillStyle}
+ * @see {@link barcodeStrokeStyle}
+ * @see {@link barcodeLineWidth}
+ * @category UI
+ */
+ set barcodeStrokeStyleBeforeVerification(style: string);
+ get barcodeStrokeStyleBeforeVerification(): string;
+ private _barcodeLineWidthBeforeVerification;
+ /**
+ * Specifies the line width of the outline of the shape which highlights a found linear barcode which has not been verified.
+ * @defaultValue `2`
+ * @see {@link barcodeFillStyleBeforeVerification}
+ * @see {@link barcodeStrokeStyleBeforeVerification}
+ * @see {@link barcodeFillStyle}
+ * @see {@link barcodeStrokeStyle}
+ * @see {@link barcodeLineWidth}
+ * @category UI
+ */
+ set barcodeLineWidthBeforeVerification(width: number);
+ get barcodeLineWidthBeforeVerification(): number;
+ /**
+ * Specifies the color used in the square-loop shape between the actual scanning area and the boundary of the video input. This shape only appears when the barcode scanning is limited to a specified region.
+ * @defaultValue `"rgba(0, 0, 0, 0.5)"`
+ * @see {@link regionMaskStrokeStyle}
+ * @see {@link regionMaskLineWidth}
+ * @category UI
+ */
+ set regionMaskFillStyle(value: string);
+ get regionMaskFillStyle(): string;
+ /**
+ * Specifies the color used to paint the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region.
+ * @defaultValue `"rgb(254, 142, 20)"`
+ * @see {@link regionMaskFillStyle}
+ * @see {@link regionMaskLineWidth}
+ * @category UI
+ */
+ set regionMaskStrokeStyle(value: string);
+ get regionMaskStrokeStyle(): string;
+ /**
+ * Specifies the width of the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region.
+ * @defaultValue `2`
+ * @see {@link regionMaskFillStyle}
+ * @see {@link regionMaskStrokeStyle}
+ * @category UI
+ */
+ set regionMaskLineWidth(value: string);
+ get regionMaskLineWidth(): string;
+ protected bFilterRegionInJs: boolean;
+ protected set region(value: null | Region | Region[]);
+ protected get region(): null | Region | Region[];
+ /**
+ * Whether to save the original image into a `HTMLCanvasElement` element. The original image refers to the actual image the library tried to read barcodes from. It can be returned by {@link getOriginalImageInACanvas}.
+ * @defaultValue `false`
+ * @example
+ * ```js
+ * scanner.ifSaveOriginalImageInACanvas = true;
+ * let results = await scanner.decode(source);
+ * document.body.append(scanner.getOriginalImageInACanvas());
+ * ```
+ * @see {@link getOriginalImageInACanvas}
+ */
+ set ifSaveOriginalImageInACanvas(value: boolean);
+ get ifSaveOriginalImageInACanvas(): boolean;
+ private createDCEInstance;
+ /** @ignore */
+ set maxCvsSideLength(value: number);
+ get maxCvsSideLength(): number;
+ private constructor();
+ /**
+ * Create a `BarcodeScanner` object.
+ * @returns A promise resolving to the created `BarcodeScanner` object.
+ * @example
+ * ```js
+ * let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
+ * ```
+ * @see {@link destroyContext}
+ * @category Initialize and Destroy
+ */
+ static createInstance(config?: any): Promise;
+ /**
+ * Decode barcodes from the current frame of the video.
+ * @returns A promise resolving to an array of {@link TextResult} that contains all the barcode results.
+ * @example
+ * ```js
+ * await scanner.showVideo();
+ * console.log(await scanner.decodeCurrentFrame());
+ * ```
+ * @see {@link TextResult}
+ * @category Decode
+ */
+ decodeCurrentFrame(config?: any): Promise;
+ /**
+ * Update runtime settings.
+ * @param settings a `RuntimeSettings` object, or a string represent one of preset templates:
+ *
+ * `speed`: fast but may miss a few codes;
+ *
+ * `coverage`: slow but try to find all codes, this is the default setting for a `BarcodeReader` instance;
+ *
+ * `balance`: between `speed` and `coverage`;
+ *
+ * `single`: optimized for scanning one single barcode from a video input, this is the default setting for a `BarcodeScanner` instance;
+ *
+ * `dense`: optimized for scanning dense barcodes such as the PDF417 on driver's license;
+ *
+ * `distance`: optimized for scanning a barcode that is placed far from the device and appear small in the video stream.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await scanner.updateRuntimeSettings('balance');
+ * let settings = await scanner.getRuntimeSettings();
+ * settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED;
+ * await scanner.updateRuntimeSettings(settings);
+ * ```
+ * @see {@link RuntimeSettings}
+ * @see {@link getRuntimeSettings}
+ * @see {@link resetRuntimeSettings}
+ * @category Runtime Settings
+ */
+ updateRuntimeSettings(settings: RuntimeSettings | string): Promise;
+ /** @ignore */
+ _bindUI(): void;
+ /** @ignore */
+ _unbindUI(): void;
+ private _onPlayed;
+ /**
+ * This event is triggered when the video stream starts playing.
+ * @event
+ * @defaultValue `null`
+ * @example
+ * ```js
+ * scanner.onPlayed = rsl=>{ console.log(rsl.width+'x'+rsl.height) };
+ * await scanner.show(); // or open, play, setCurrentCamera, like these.
+ * ```
+ */
+ set onPlayed(value: (info: ScannerPlayCallbackInfo) => void);
+ get onPlayed(): (info: ScannerPlayCallbackInfo) => void;
+ /**
+ * Returns infomation of all available cameras on the device.
+ * @returns A promise resolving to an array of {@link VideoDeviceInfo} objects.
+ * @example
+ * ```js
+ * let cameras = await scanner.getAllCameras();
+ * if(cameras.length){
+ * await scanner.setCurrentCamera(cameras[0]);
+ * }
+ * ```
+ * @see {@link VideoDeviceInfo}
+ * @see {@link getCurrentCamera}
+ * @category Camera Settings
+ */
+ getAllCameras(): Promise;
+ /**
+ * Returns information about the current camera.
+ * @returns A promise resolving to a {@link VideoDeviceInfo} object.
+ * @example
+ * ```js
+ * let camera = await scanner.getCurrentCamera();
+ * ```
+ * @see {@link VideoDeviceInfo}
+ * @see {@link getAllCameras}
+ * @see {@link setCurrentCamera}
+ * @category Camera Settings
+ */
+ getCurrentCamera(): Promise;
+ /**
+ * Chooses a camera as the video source.
+ * @param cameraInfoOrDeviceId Specifies the camera.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @example
+ * ```js
+ * let cameras = await scanner.getAllCameras();
+ * if(cameras.length){
+ * await scanner.setCurrentCamera(cameras[0]);
+ * }
+ * ```
+ * @fires {@link onPlayed}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @see {@link getCurrentCamera}
+ * @category Camera Settings
+ */
+ setCurrentCamera(cameraInfoOrDeviceId: any): Promise;
+ /**
+ * Returns the resolution of the current video input.
+ * @returns An array of two numbers representing the resolution.
+ * @example
+ * ```js
+ * let rsl = await scanner.getResolution();
+ * console.log(rsl[0] + " x " + rsl[1]);
+ * ```
+ * @see {@link setResolution}
+ * @category Camera Settings
+ */
+ getResolution(): number[];
+ /**
+ * Sets the resolution of the current video input. If the specified resolution is not exactly supported, the closest resolution will be applied.
+ *
+ * If called before `open()` or `show()`, the camera will use the set resolution when it opens. Otherwise, the default resolution is used, which is 1280 x 720 on mobile devices or 1920 x 1080 on desktop.
+ * @param width Specifies the horizontal resolution.
+ * @param height Specifies the vertical resolution.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @example
+ * ```js
+ * await scanner.setResolution(width, height);
+ * ```
+ * @fires {@link onPlayed}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @see {@link getResolution}
+ * @category Camera Settings
+ */
+ setResolution(width: number | number[], height: number): Promise;
+ /**
+ * Returns the current video settings.
+ * @returns A `MediaStreamConstraints` object.
+ * @see {@link updateVideoSettings}
+ * @category Camera Settings
+ */
+ getVideoSettings(): MediaStreamConstraints;
+ /**
+ * Modify and update video settings.
+ * @param mediaStreamConstraints Specifies the new video settings.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @example
+ * ```js
+ * await scanner.updateVideoSettings({ video: {width: {ideal: 1280}, height: {ideal: 720}, facingMode: {ideal: 'environment'}} });
+ * ```
+ * @see {@link ScannerPlayCallbackInfo}
+ * @see {@link getVideoSettings}
+ * @category Camera Settings
+ */
+ updateVideoSettings(mediaStreamConstraints: any): Promise;
+ /**
+ * Indicates whether the camera is turned on.
+ * @returns A boolean indicates whether the camera is turned on.
+ * @example
+ * ```js
+ * await scanner.show(); // or open(), showVideo(), openVideo();
+ * console.assert(scanner.isOpen(), "scanner should be opened.");
+ * await scanner.hide(); // or close();
+ * console.assert(!scanner.isOpen(), "scanner should be closed.");
+ * ```
+ * @category Open and Close
+ */
+ isOpen(): boolean;
+ /**
+ * Sets the `object-fit` CSS property of the video element.
+ * @param value Specify the new fit type. At present, only "cover" and "contain" are allowed.
+ * @see {@link getVideoFit}
+ */
+ setVideoFit(value: string): void;
+ /**
+ * Returns the value of the object-fit CSS property of the video element.
+ * @returns The value of the object-fit CSS property.
+ * @see {@link setVideoFit}
+ */
+ getVideoFit(): string;
+ /**
+ * Whether to show the scan region mask.
+ * @defaultValue `true`
+ */
+ set ifShowScanRegionMask(value: boolean);
+ get ifShowScanRegionMask(): boolean;
+ /**
+ * Returns or sets whether to save the last used camera and resolution.
+ * This feature makes use of the `localStorage` of the browser.
+ *
+ * Note: This feature only works on mainstream browsers like Chrome, Firefox and Safari. Other browsers may change the device IDs dynamically thus making it impossible to track the camera.
+ * @defaultValue `false`
+ */
+ set ifSaveLastUsedCamera(value: boolean);
+ get ifSaveLastUsedCamera(): boolean;
+ /**
+ * Returns or sets whether to skip camera inspection at initialization to save time.
+ * Note that if a previously used camera is already available in the `localStorage`, the inspection is skipped automatically. Read more on {@link ifSaveLastUsedCamera}.
+ * @defaultValue `false`
+ */
+ set ifSkipCameraInspection(value: boolean);
+ get ifSkipCameraInspection(): boolean;
+ /**
+ * Stops the video and releases the camera.
+ * @example
+ * ```js
+ * scanner.stop()
+ * // *** a lot of work ***
+ * await scanner.play();
+ * ```
+ * @see {@link play}
+ * @category Play and Pause
+ */
+ stop(): void;
+ /**
+ * Pauses the video without releasing the camera.
+ * @example
+ * ```js
+ * scanner.pause();
+ * // *** a lot of work ***
+ * await scanner.play();
+ * ```
+ * @see {@link play}
+ * @category Play and Pause
+ */
+ pause(): void;
+ /**
+ * Play the video if it is already open but paused or stopped. If the video is already playing, it will start again.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @fires [[onPlayed]]
+ * @example
+ * ```js
+ * scanner.pause(); // or scanner.stop()
+ * // *** a lot of work ***
+ * await scanner.play();
+ * ```
+ * @see {@link ScannerPlayCallbackInfo}
+ * @see {@link stop}
+ * @see {@link pause}
+ * @category Play and Pause
+ */
+ play(deviceId?: string, width?: number, height?: number): Promise;
+ /**
+ * Pause continuous scanning but keep the video stream.
+ * @param options Options to configure how the pause works. At present, it only contains one property `keepResultsHighlighted` which, when set to `true`, will keep the barcodes found on the frame (at the time of the pause) highlighted.
+ * @see {@link resumeScan}
+ * @category Play and Pause
+ */
+ pauseScan(options?: any): void;
+ /**
+ * Resumes the decoding process.
+ * @see {@link pauseScan}
+ * @category Play and Pause
+ */
+ resumeScan(): void;
+ /**
+ * Inspects and returns the capabilities of the current camera.
+ *
+ * Note: At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported).
+ * Also, it should be called when a camera is open.
+ * @returns A `MediaTrackCapabilities` object which specifies the values or range of values for each constrainable property of the current camera.
+ * @example
+ * ```
+ * scanner.getCapabilities()
+ * // Result sample
+ * {
+ * "aspectRatio":{"max":3840,"min":0.000462962962962963},
+ * "colorTemperature":{max: 7000, min: 2850, step: 50},
+ * "deviceId":"1e...3af7",
+ * "exposureCompensation": {max: 2.0000040531158447, min: -2.0000040531158447, step: 0.16666699945926666},
+ * "exposureMode":["continuous","manual"],
+ * "facingMode":["environment"],
+ * "focusMode":["continuous","single-shot","manual"],
+ * "frameRate":{"max":30,"min":0},
+ * "groupId":"71...a935",
+ * "height":{"max":2160,"min":1},
+ * "resizeMode":["none","crop-and-scale"],
+ * "torch":true,
+ * "whiteBalanceMode":["continuous","manual"],
+ * "width":{"max":3840,"min":1},
+ * "zoom":{max: 606, min: 100, step: 2}
+ * }
+ * ```
+ * @category Camera Settings
+ */
+ getCapabilities(): MediaTrackCapabilities;
+ /** @ignore */
+ getCameraSettings(): MediaTrackSettings;
+ /** @ignore */
+ getConstraints(): MediaTrackConstraints;
+ /**
+ * @ignore
+ * Set the camera capabilities.
+ * Only available when the scanner is open.
+ * It's a low-level API, usually you can use the wrapped APIs instead.
+ * ```js
+ * await scanner.applyConstraints({ frameRate: { ideal:5 } });
+ * ```
+ */
+ applyConstraints(constraints: MediaTrackConstraints): Promise;
+ /**
+ * Turns on the torch/flashlight if the current camera supports it. This method should be called when the camera is turned on.
+ *
+ * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported.
+ * @returns A promise that resolves when the operation succeeds.
+ * @see {@link turnOffTorch}
+ * @see {@link getCapabilities}
+ * @category Camera Settings
+ */
+ turnOnTorch(): Promise;
+ /**
+ * Turns off the torch/flashlight.
+ *
+ * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.
+ * @see {@link turnOnTorch}
+ * @category Camera Settings
+ */
+ turnOffTorch(): Promise;
+ /**
+ * Adjusts the color temperature.
+ *
+ * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.
+ * @param value Specifies the new color temperature.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await scanner.setColorTemperature(5000);
+ * ```
+ * @see {@link getColorTemperature}
+ * @see {@link getCapabilities}
+ * @category Camera Settings
+ */
+ setColorTemperature(value: number): Promise;
+ /**
+ * Returns the color temperature of the selected camera. This method should be called when the camera is turned on.
+ *
+ * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported.
+ * @returns Color temperature of the selected camera.
+ * @see {@link setColorTemperature}
+ * @category Camera Settings
+ */
+ getColorTemperature(): number;
+ /**
+ * Sets the exposure compensation index.
+ *
+ * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.
+ * @param value Specifies the new exposure compensation index.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await scanner.setExposureCompensation(-0.7);
+ * ```
+ * @see {@link getExposureCompensation}
+ * @see {@link getCapabilities}
+ * @category Camera Settings
+ */
+ setExposureCompensation(value: number): Promise;
+ /**
+ * Returns the exposure compensation index of the selected camera. This method should be called when the camera is turned on.
+ *
+ * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported.
+ * @returns Exposure compensation index of the selected camera.
+ * @see {@link setExposureCompensation}
+ * @category Camera Settings
+ */
+ getExposureCompensation(): number;
+ /**
+ * Sets current zoom value.
+ *
+ * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.
+ * @param settings Specifies the new zoom value.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await scanner.setZoom(2);
+ * ```
+ * @see {@link getZoomSettings}
+ * @see {@link resetZoom}
+ * @see {@link getCapabilities}
+ * @category Camera Settings
+ */
+ setZoom(settings: number | {
+ factor: number;
+ centerPoint?: {
+ x: string;
+ y: string;
+ };
+ }): Promise;
+ /**
+ * Returns the zoom settings.
+ * @returns An object that describes the zoom settings. As of version 3.2, it contains only the zoom factor.
+ * @see {@link setZoom}
+ * @category Camera Settings
+ */
+ getZoomSettings(): {
+ factor: number;
+ };
+ /**
+ * Resets the zoom level of the video.
+ * @returns A promise that resolves when the operation succeeds.
+ * @see {@link setZoom}
+ * @category Camera Settings
+ */
+ resetZoom(): Promise;
+ /**
+ * Adjusts the frame rate.
+ *
+ * At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.
+ * @param value Specifies the new frame rate.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await scanner.setFrameRate(10);
+ * ```
+ * @see {@link getFrameRate}
+ * @see {@link getCapabilities}
+ * @category Camera Settings
+ */
+ setFrameRate(value: number): Promise;
+ /**
+ * Returns the real-time frame rate.
+ * @returns The calculated real-time frame rate.
+ * @see {@link setFrameRate}
+ * @category Camera Settings
+ */
+ getFrameRate(): number;
+ /**
+ * Sets the focus mode and focus distance of the camera.
+ *
+ * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.
+ * @param settings Specifies the focus mode, the available values include `continuous` and `manual`.
+ * @param distance Specifies the focus distance, only required when the `mode` is set to `manual`.
+ * @returns A promise that resolves when the operation succeeds.
+ * @example
+ * ```js
+ * await scanner.setFocus("manual", 5);
+ * ```
+ * @see {@link getFocusSettings}
+ * @see {@link getCapabilities}
+ * @category Camera Settings
+ */
+ setFocus(settings: string | {
+ mode: string;
+ } | {
+ mode: "manual";
+ distance: number;
+ } | {
+ mode: "manual";
+ area: {
+ centerPoint: {
+ x: string;
+ y: string;
+ };
+ width?: string;
+ height?: string;
+ };
+ }, distance?: number): Promise;
+ /**
+ * @deprecated Use {@link getFocusSettings} instead.
+ */
+ getFocus(): Object;
+ /**
+ * Returns the focus settings.
+ * @returns The current focus settings.
+ * @see {@link setFocus}
+ * @category Camera Settings
+ */
+ getFocusSettings(): Object;
+ protected _loopReadVideo(): Promise;
+ /**
+ * start dce fetching frame loop, and get frame from frame queue
+ * @ignore
+ */
+ protected _getVideoFrame(): DCEFrame;
+ /**
+ * Binds UI, turns on the camera and starts decoding.
+ *
+ * This method does not change the original state of the UI: if it doesn't exist in the DOM tree, nothing shows up on the page; if it exists in the DOM tree, it may or may not show up depending on its original state.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @fires {@link onPlayed}
+ * @example
+ * ```js
+ * await scanner.setUIElement(document.getElementById("my-barcode-scanner"));
+ * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); };
+ * await scanner.open();
+ * // await scanner.close();
+ * ```
+ * @see {@link close}
+ * @see {@link hide}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @category Open and Close
+ */
+ open(): Promise;
+ /**
+ * Bind UI, open the camera, but not decode.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @fires {@link onPlayed}
+ * @example
+ * ```js
+ * await scanner.setUIElement(document.getElementById("my-barcode-scanner"));
+ * await scanner.openVideo();
+ * console.log(await scanner.decodeCurrentFrame());
+ * // await scanner.close();
+ * ```
+ * @see {@link close}
+ * @see {@link hide}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @category Open and Close
+ */
+ openVideo(): Promise;
+ /**
+ * Stops decoding, releases camera, unbinds and hides UI.
+ * @example
+ * ```js
+ * await scanner.open();
+ * await scanner.close();
+ * ```
+ * @example
+ * ```js
+ * await scanner.openVideo();
+ * await scanner.close();
+ * ```
+ * @see {@link hide}
+ * @category Open and Close
+ */
+ close(): void;
+ /**
+ * Binds and shows UI, opens the camera and starts decoding.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @fires {@link onPlayed}
+ * @example
+ * ```js
+ * await scanner.setUIElement("https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode/dist/dbr.ui.html");
+ * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); };
+ * await scanner.show();
+ * // await scanner.hide();
+ * ```
+ * @see {@link close}
+ * @see {@link hide}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @category Open and Close
+ */
+ show(): Promise;
+ /**
+ * Bind UI, open the camera, but not decode, and remove the UIElement `display` style if the original style is `display:none;`.
+ * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object.
+ * @fires {@link onPlayed}
+ * @example
+ * ```js
+ * await scanner.showVideo()
+ * console.log(await scanner.decodeCurrentFrame());
+ * // await scanner.hide();
+ * ```
+ * @see {@link close}
+ * @see {@link hide}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @category Open and Close
+ */
+ showVideo(): Promise;
+ /**
+ * Stops decoding, releases camera and unbinds and hides UI.
+ * @example
+ * ```js
+ * await scanner.show();
+ * await scanner.hidee();
+ * ```
+ * @example
+ * ```js
+ * await scanner.showVideo();
+ * await scanner.hide();
+ * ```
+ * @see {@link close}
+ * @see {@link ScannerPlayCallbackInfo}
+ * @category Open and Close
+ */
+ hide(): void;
+ /**
+ * Shows a Tip message.
+ * @param x Specifies the x coordinate of the Tip message.
+ * @param y Specifies the y coordinate of the Tip message.
+ * @param width Specifies the width of the Tip message, wrapping if the message is too long.
+ * @param initialMessage Optional. The initial message.
+ * @param duration Optional. The time during which a Tip message is displayed. The duration is reset each time the message is updated. Default value is `3000`.
+ * @param autoShowSuggestedTip Optional. Whether or not the Tip box is updated automatically when a tip is suggested. A tip is usually suggested by another SDK such as Dynamsoft Barcode Reader.
+ * @example
+ * ```js
+ * scanner.showTip(500, 200, 500, "The camera is too far away, please move closer!", 3000, true);
+ * ```
+ * @see {@link hideTip}
+ */
+ showTip(x: number, y: number, width: number, initialMessage?: string, duration?: number, autoShowSuggestedTip?: boolean): void;
+ /**
+ * Hides the Tip message.
+ * @see {@link showTip}
+ */
+ hideTip(): void;
+ /**
+ * Changes the Tip message.
+ * @param message Specifies a new message as the Tip.
+ */
+ updateTipMessage(message: string): void;
+ /**
+ * Enables manual camera focus when clicking/tapping on the video.
+ *
+ * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported).
+ * @see {@link disableTapToFocus}
+ * @see {@link isTapToFocusEnabled}
+ */
+ enableTapToFocus(): Promise;
+ /**
+ * Disables manual camera focus when clicking/tapping on the video.
+ * @see {@link enableTapToFocus}
+ * @see {@link isTapToFocusEnabled}
+ */
+ disableTapToFocus(): void;
+ /**
+ * Returns whether clicking/tapping on the video invokes the camera to focus.
+ * @returns `true` means clicking/tapping on the video will invoke the camera to focus. `false` means clicking/tapping on the video does nothing.
+ * @see {@link enableTapToFocus}
+ * @see {@link disableTapToFocus}
+ */
+ isTapToFocusEnabled(): boolean;
+ /**
+ * Converts coordinates of a barcode location to the coordinates relative to the top left point of the entire document.
+ *
+ * Note: Call this method only after `scanner` is open.
+ * @param point The coordinates to convert.
+ * @returns The converted coordinates.
+ * @see {@link convertToClientCoordinates}
+ */
+ convertToPageCoordinates(point: {
+ x: number;
+ y: number;
+ }): {
+ x: number;
+ y: number;
+ };
+ /**
+ * Converts coordinates of a barcode location to the coordinates within the application's viewport at which the event occurred (as opposed to the coordinate within the page).
+ *
+ * Note: Call this method only after `scanner` is open.
+ * @param point The coordinates to convert.
+ * @returns The converted coordinates.
+ * @see {@link convertToClientCoordinates}
+ */
+ convertToClientCoordinates(point: {
+ x: number;
+ y: number;
+ }): {
+ x: number;
+ y: number;
+ };
+ /**
+ * Destroys the `BarcodeScanner` instance. If your page needs to create a new instance from time to time, don't forget to destroy unused old instances.
+ * @see {@link isContextDestroyed}
+ * @category Initialize and Destroy
+ */
+ destroyContext(): void;
+}
+
+declare enum EnumBarcodeColourMode {
+ BICM_DARK_ON_LIGHT = 1,
+ BICM_LIGHT_ON_DARK = 2,
+ BICM_DARK_ON_DARK = 4,
+ BICM_LIGHT_ON_LIGHT = 8,
+ BICM_DARK_LIGHT_MIXED = 16,
+ BICM_DARK_ON_LIGHT_DARK_SURROUNDING = 32,
+ BICM_SKIP = 0,
+ BICM_REV = 2147483648
+}
+
+declare enum EnumBarcodeComplementMode {
+ BCM_AUTO = 1,
+ BCM_GENERAL = 2,
+ BCM_SKIP = 0,
+ BCM_REV = 2147483648
+}
+
+declare enum EnumClarityCalculationMethod {
+ ECCM_CONTRAST = 1
+}
+
+declare enum EnumClarityFilterMode {
+ CFM_GENERAL = 1
+}
+
+declare enum EnumColourClusteringMode {
+ CCM_AUTO = 1,
+ CCM_GENERAL_HSV = 2,
+ CCM_SKIP = 0,
+ CCM_REV = 2147483648
+}
+
+declare enum EnumColourConversionMode {
+ CICM_GENERAL = 1,
+ CICM_SKIP = 0,
+ CICM_REV = 2147483648
+}
+
+declare enum EnumConflictMode {
+ CM_IGNORE = 1,
+ CM_OVERWRITE = 2
+}
+
+declare enum EnumDeblurMode {
+ DM_SKIP = 0,
+ DM_DIRECT_BINARIZATION = 1,
+ DM_THRESHOLD_BINARIZATION = 2,
+ DM_GRAY_EQUALIZATION = 4,
+ DM_SMOOTHING = 8,
+ DM_MORPHING = 16,
+ DM_DEEP_ANALYSIS = 32,
+ DM_SHARPENING = 64,
+ DM_BASED_ON_LOC_BIN = 128,
+ DM_SHARPENING_SMOOTHING = 256
+}
+
+declare enum EnumDeformationResistingMode {
+ DRM_AUTO = 1,
+ DRM_GENERAL = 2,
+ DRM_BROAD_WARP = 4,
+ DRM_LOCAL_REFERENCE = 8,
+ DRM_DEWRINKLE = 16,
+ DRM_SKIP = 0,
+ DRM_REV = 2147483648
+}
+
+declare enum EnumDPMCodeReadingMode {
+ DPMCRM_AUTO = 1,
+ DPMCRM_GENERAL = 2,
+ DPMCRM_SKIP = 0,
+ DPMCRM_REV = 2147483648
+}
+
+declare enum EnumGrayscaleTransformationMode {
+ GTM_INVERTED = 1,
+ GTM_ORIGINAL = 2,
+ GTM_SKIP = 0,
+ GTM_REV = 2147483648
+}
+
+declare enum EnumImagePreprocessingMode {
+ IPM_AUTO = 1,
+ IPM_GENERAL = 2,
+ IPM_GRAY_EQUALIZE = 4,
+ IPM_GRAY_SMOOTH = 8,
+ IPM_SHARPEN_SMOOTH = 16,
+ IPM_MORPHOLOGY = 32,
+ IPM_SKIP = 0,
+ IPM_REV = 2147483648
+}
+
+declare enum EnumIMResultDataType {
+ IMRDT_IMAGE = 1,
+ IMRDT_CONTOUR = 2,
+ IMRDT_LINESEGMENT = 4,
+ IMRDT_LOCALIZATIONRESULT = 8,
+ IMRDT_REGIONOFINTEREST = 16,
+ IMRDT_QUADRILATERAL = 32
+}
+
+declare enum EnumIntermediateResultSavingMode {
+ IRSM_MEMORY = 1,
+ IRSM_FILESYSTEM = 2,
+ IRSM_BOTH = 4
+}
+
+declare enum EnumQRCodeErrorCorrectionLevel {
+ QRECL_ERROR_CORRECTION_H = 0,
+ QRECL_ERROR_CORRECTION_L = 1,
+ QRECL_ERROR_CORRECTION_M = 2,
+ QRECL_ERROR_CORRECTION_Q = 3
+}
+
+declare enum EnumRegionPredetectionMode {
+ RPM_AUTO = 1,
+ RPM_GENERAL = 2,
+ RPM_GENERAL_RGB_CONTRAST = 4,
+ RPM_GENERAL_GRAY_CONTRAST = 8,
+ RPM_GENERAL_HSV_CONTRAST = 16,
+ RPM_SKIP = 0,
+ RPM_REV = 2147483648
+}
+
+declare enum EnumResultType {
+ RT_STANDARD_TEXT = 0,
+ RT_RAW_TEXT = 1,
+ RT_CANDIDATE_TEXT = 2,
+ RT_PARTIAL_TEXT = 3
+}
+
+declare enum EnumTextFilterMode {
+ TFM_AUTO = 1,
+ TFM_GENERAL_CONTOUR = 2,
+ TFM_SKIP = 0,
+ TFM_REV = 2147483648
+}
+
+declare enum EnumTextureDetectionMode {
+ TDM_AUTO = 1,
+ TDM_GENERAL_WIDTH_CONCENTRATION = 2,
+ TDM_SKIP = 0,
+ TDM_REV = 2147483648
+}
+
+export { BarcodeReader, BarcodeScanner, DSImage, EnumBarcodeColourMode, EnumBarcodeComplementMode, EnumBarcodeFormat, EnumBarcodeFormat_2, EnumBinarizationMode, EnumClarityCalculationMethod, EnumClarityFilterMode, EnumColourClusteringMode, EnumColourConversionMode, EnumConflictMode, EnumDPMCodeReadingMode, EnumDeblurMode, EnumDeformationResistingMode, EnumErrorCode, EnumGrayscaleTransformationMode, EnumIMResultDataType, EnumImagePixelFormat, EnumImagePreprocessingMode, EnumIntermediateResultSavingMode, EnumIntermediateResultType, EnumLocalizationMode, EnumQRCodeErrorCorrectionLevel, EnumRegionPredetectionMode, EnumResultCoordinateType, EnumResultType, EnumScaleUpMode, EnumTerminatePhase, EnumTextFilterMode, EnumTextResultOrderMode, EnumTextureDetectionMode, ImageSource, Region, RuntimeSettings, ScanSettings, TextResult };
diff --git a/dist/dbr.js b/dist/dbr.js
index 22ebc22..5ebacc6 100644
--- a/dist/dbr.js
+++ b/dist/dbr.js
@@ -2,20 +2,21 @@
* Dynamsoft JavaScript Library
* @product Dynamsoft Barcode Reader JS Edition
* @website http://www.dynamsoft.com
- * @copyright Copyright 2023, Dynamsoft Corporation
+ * @copyright Copyright 2024, Dynamsoft Corporation
* @author Dynamsoft
- * @version 9.6.32 (js 20231027)
+ * @version 9.6.42 (js 20240426)
* @fileoverview Dynamsoft JavaScript Library for Barcode Reader
* More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/
*/
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";const t="undefined"==typeof self,i=t?{}:self;let r,n,s,o,a;if("undefined"!=typeof navigator&&(r=navigator,n=r.userAgent,s=r.platform,o=r.mediaDevices),!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:s,search:"Win"},Mac:{str:s},Linux:{str:s}};let i="unknownBrowser",o=0,l="unknownOS";for(let t in e){const r=e[t]||{};let s=r.str||n,a=r.search||t,l=r.verStr||n,h=r.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(a)){i=t;for(let e of h){let t=l.indexOf(e);if(-1!=t){o=parseFloat(l.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||n,s=i.search||e;if(-1!=r.indexOf(s)){l=e;break}}"Linux"==l&&-1!=n.indexOf("Windows NT")&&(l="HarmonyOS"),a={browser:i,version:o,OS:l}}t&&(a={browser:"ssr",version:0,OS:"ssr"});const l="undefined"!=typeof WebAssembly&&n&&!(/Safari/.test(n)&&!/Chrome/.test(n)&&/\(.+\s11_2_([2-6]).*\)/.test(n)),h=!("undefined"==typeof Worker),c=!(!o||!o.getUserMedia),u=async()=>{let e=!1;if(c)try{(await o.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===a.browser&&a.version>66||"Safari"===a.browser&&a.version>13||"OPR"===a.browser&&a.version>43||"Edge"===a.browser&&a.version;const d=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),f=" is not allowed to change after `createInstance` or `loadWasm` is called.",g=!t&&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"))||"",_=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",p=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;class C extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(w(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,w(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}var x=function(){this.init()};x.prototype={init:function(){var e=this||T;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||T;if(e=parseFloat(e),t.ctx||F(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,T.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,F()),e},codecs:function(e){return(this||T)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||T;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||T,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),s=n&&parseInt(n[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),l=o&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(s||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||T;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),h=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-l),c=1e3*h/Math.abs(o._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var f=function(){o._paused=!1,o._seek=l,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(l>=d)){var g=o._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(o);var e=o._muted||i._muted?0:o._volume;g.gain.setValueAtTime(e,T.ctx.currentTime),o._playStart=T.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,l,86400):g.bufferSource.noteGrainOn(0,l,h):o._loop?g.bufferSource.start(0,l,86400):g.bufferSource.start(0,l,h),c!==1/0&&(i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c)),t||setTimeout((function(){i._emit("play",o._id),i._loadQueue()}),0)};"running"===T.state&&"interrupted"!==T.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=l,g.muted=o._muted||i._muted||T._muted||g.muted,g.volume=o._volume*T.volume(),g.playbackRate=o._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",o._id)})).catch((function(){i._playLock=!1,i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",o._id)),g.playbackRate=o._rate,g.paused)return void i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c):(i._endTimers[o._id]=function(){i._ended(o),g.removeEventListener("ended",i._endTimers[o._id],!1)},g.addEventListener("ended",i._endTimers[o._id],!1))}catch(e){i._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&T._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(T._canPlayEvent,v,!1)};g.addEventListener(T._canPlayEvent,v,!1),i._clearTimer(o._id)}}return o._id}i._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/h:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=l*n,a=Math.round(100*a)/100,a=l<0?Math.max(i,a):Math.min(i,a),o._webAudio?e._volume=a:o.volume(a,e._id,!0),s&&(o._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,o.volume(i,e._id),o._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(T.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var s=r._getSoundIds(t),o=0;o=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var o=i._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?T.ctx.currentTime-o._playStart:0,l=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(l+a*Math.abs(o._rate))}return o._node.currentTime}var h=i.playing(t);h&&i.pause(t,!0),o._seek=e,o._ended=!1,i._clearTimer(t),i._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var c=function(){h&&i.play(t,!0),i._emit("seek",t)};if(h&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&T._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return O&&n&&delete O[e._src],T.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s=0;s--)n[s].id&&n[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[s].fn),0),n[s].once&&r.off(e,n[s].fn,n[s].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(T._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=T._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(T._navigator&&T._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var I=function(e){this._parent=e,this.init()};I.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++T._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=T._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===T.ctx.createGain?T.ctx.createGainNode():T.ctx.createGain(),e._node.gain.setValueAtTime(i,T.ctx.currentTime),e._node.paused=!0,e._node.connect(T.masterGain)):T.noAudio||(e._node=T._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(T._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*T.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++T._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(T._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var O={},A=function(e){var t=e._src;if(O[t])return e._duration=O[t].duration,void M(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(O[t._src]=e,M(t,e)):i()};"undefined"!=typeof Promise&&1===T.ctx.decodeAudioData.length?T.ctx.decodeAudioData(e).then(r).catch(i):T.ctx.decodeAudioData(e,r,i)},M=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},F=function(){if(T.usingWebAudio){try{"undefined"!=typeof AudioContext?T.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?T.ctx=new webkitAudioContext:T.usingWebAudio=!1}catch(e){T.usingWebAudio=!1}T.ctx||(T.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(T._navigator&&T._navigator.platform),t=T._navigator&&T._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(T._navigator&&T._navigator.userAgent.toLowerCase());T._navigator&&!r&&(T.usingWebAudio=!1)}T.usingWebAudio&&(T.masterGain=void 0===T.ctx.createGain?T.ctx.createGainNode():T.ctx.createGain(),T.masterGain.gain.setValueAtTime(T._muted?0:T._volume,T.ctx.currentTime),T.masterGain.connect(T.ctx.destination)),T._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,s,o){var a=this;if(!a.ctx||!a.ctx.listener)return a;var l=a._orientation;return i="number"!=typeof i?l[1]:i,r="number"!=typeof r?l[2]:r,n="number"!=typeof n?l[3]:n,s="number"!=typeof s?l[4]:s,o="number"!=typeof o?l[5]:o,"number"!=typeof e?l:(a._orientation=[e,i,r,n,s,o],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(s,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(o,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,s,o),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var o=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}})}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+f);i._license=t})(P,e)}static get productKeys(){return this._license}static set productKeys(e){P.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){P.license=e}static get organizationID(){return this._license}static set organizationID(e){P.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+f);i._sessionPassword=t})(P,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:l,worker:h,getUserMedia:c,camera:await u(),browser:a.browser,version:a.version,OS:a.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");P._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+f);i._licenseServer=p(t)})(P,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+f);i._deviceFriendlyName=t||""})(P,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");P.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=P._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",P.engineResourcePath)}static set defaultUIElementURL(e){P._defaultUIElementURL=e}static _fireHTTPSWarnning(){P.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{P.onWarning&&P.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new E({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;P._onLog&&P._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),i=null;if(t&&t.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:l}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),P.recalculateResultLocation(i,r,n,a,l,s,o)}if(this._drawResults(i,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(P._onLog&&P._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!P.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:r,sp:n,rmk:s}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,r,n=t._license||"",s=JSON.parse(JSON.stringify(t._licenseServer)),o=t._sessionPassword,a=0;if(n.startsWith("t")||n.startsWith("f"))a=0;else if(0===n.length||n.startsWith("P")||n.startsWith("L")||n.startsWith("Y")||n.startsWith("A"))a=1;else{a=2;const t=n.indexOf(":");if(-1!=t&&(n=n.substring(t+1)),n.startsWith("DLS2")){let t;try{let e=n.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(n=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof n&&(n=JSON.stringify(n)),0===s.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),s=p(e)}!o&&t.sessionPassword&&(o=t.sessionPassword),e=t.remark}("200001"===n||n.startsWith("200001-"))&&(s&&s.length||(n="")),n||(a=1)}if(a&&(i.crypto||(r="Please upgrade your browser to support online key."),i.crypto.subtle||(r="Require https to use online key in this browser.")),r){if(1!==a)throw new Error(r);a=0,console.warn(r),t._lastErrorCode=-1,t._lastErrorString=r}return 1===a&&(n="",console.warn("Applying for a public trial license ...")),{lt:a,l:n,ls:s,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+f)})(P);this._pLoad.task=async(i,o)=>{let l=P.engineResourcePath+P._workerName;P.engineResourcePath.startsWith(location.origin)||(l=await fetch(l).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),P._dbrWorker=new Worker(l),P._dbrWorker.onerror=e=>{let t=new Error(e.message);o(t)},P._dbrWorker.onmessage=async t=>{let r=t.data?t.data:t;switch(r.type){case"log":P._onLog&&P._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,n=!1;1===e&&(n=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(P._dbrWorker.onerror=null,P._version=r.version+"(JS "+P._jsVersion+"."+P._jsEditVersion+")",P._onLog&&P._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(t=new Error(r.message),t.stack=r.stack+"\n"+t.stack,t.ltsErrorCode=r.ltsErrorCode,n||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&P.showDialog(r.success?"warn":"error",r.message),r.success?i():o(t);break}case"task":{let e=r.id,t=r.body;try{P._taskCallbackMap.get(e)(t),P._taskCallbackMap.delete(e)}catch(t){throw P._taskCallbackMap.delete(e),t}break}default:P._onLog&&P._onLog(t)}},P._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:P.engineResourcePath,bUseFullFeature:P._bUseFullFeature,bd:P._bWasmDebug,v:P._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:a,cv:P.authCacheVersion,fn:P.deviceFriendlyName,ls:r,sp:n,rmk:s})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!h&&e.classList.contains("dls-license-icon-close"))h=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),s=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),a=t.substring(i+1,r);o.innerText=a;let l=t.substring(n+1,s);o.setAttribute("href",l),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(s+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await P.loadWasm(),await new Promise(((t,i)=>{let r=P._nextTaskID++;P._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),P._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){const e=new P;return e._instanceID=await P.createInstanceInWorker(),P._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){P._onLog&&P._onLog("decode(source: any)"),P._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):P.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):P.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,s,o){return await new Promise(((a,l)=>{let h=P._nextTaskID++;P._taskCallbackMap.set(h,(e=>{if(e.success){let t,i=P._onLog?Date.now():0;P._onLog&&P._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return l(e)}if(P._onLog){let e=Date.now();P._onLog("DBR getting message from worker timestamp: "+i),P._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),P._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),P._onLog("Handling results from DBR worker costs: "+(e-i)),P._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}})),this._timeEnterInnerDBR=Date.now(),P._onLog&&P._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),P._dbrWorker.postMessage({type:"decodeBuffer",id:h,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),P._onLog&&o&&o.timeStamp&&P._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){P._onLog&&P._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,i,r,n,s,o)}async decodeBuffer(e,t,i,r,n,s,o){let a;return P._onLog&&P._onLog("decodeBuffer(buffer,width,height,stride,format)"),P._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,i,r,n,s,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,s,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,i,r,n,s,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=P._nextTaskID++;P._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),P._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=5,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=9,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=i.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!P._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=i.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,i.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(i.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,t)=>{let r=P._nextTaskID++;P._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=L,await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=L,await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!P._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!P._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=P._nextTaskID++;P._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),P._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){P._onLog&&P._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){P._onLog&&P._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,s=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_Canvas(t,i){if(P._onLog&&P._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,0,i)}async _decode_Video(e,t){if(P._onLog&&P._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,s=e.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_DCEFrame(t,i){if(P._onLog&&P._onLog("_decode_DCEFrame(dceFrame)"),!P.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:n,height:s,colorMode:o,pixelFormat:a,stride:l,timeStamp:h}=t;let c;c=i&&i.bCopyData?new Uint8Array(t.data):t.data;let u=null;if(i?(u=JSON.parse(JSON.stringify(i)),u.timeStamp=h):u={timeStamp:h},a&&l)if("grey"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,l,e.EnumImagePixelFormat.IPF_ABGR_8888,0,u);else{if("bgra"!==a)throw new Error(`Pixel format '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(c,n,s,l,e.EnumImagePixelFormat.IPF_ARGB_8888,0,u)}else if("grey"===o)r=await this._decodeBuffer_Uint8Array(c,n,s,n,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===o)r=await this._decodeBuffer_Uint8Array(c,n,s,4*n,e.EnumImagePixelFormat.IPF_ABGR_8888,0,u);else{if("bgra"!==o)throw new Error(`Color mode '${o}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(c,n,s,4*n,e.EnumImagePixelFormat.IPF_ARGB_8888,0,u)}return r}async _decode_DSImage(t,i){if(P._onLog&&P._onLog("_decode_DSImage(dsImage)"),!P.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw P._onLog&&P._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,s,o){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*s,e.x2*=.01*s,e.x3*=.01*s,e.x4*=.01*s,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let l=s/r,h=o/n;e.x1=e.x1/l+t,e.x2=e.x2/l+t,e.x3=e.x3/l+t,e.x4=e.x4/l+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}static BarcodeReaderException(t,i){let r,n=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(n=t,r=new Error(i)):r=new Error(t),r.code=n,r}_handleRetJsonString(t){let i=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!P._setWarnnedEx.has(t.description)&&(P._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw P.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=P._nextTaskID++;P._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return s(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),P._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let s=P._nextTaskID++;P._taskCallbackMap.set(s,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),P._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),i=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let n;switch(P._onLog&&P._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:n=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;n=new Uint8ClampedArray(4*e);for(let t=0;t=i)break;n[o]=n[o+1]=n[o+2]=(128&e)/128*255,n[o+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!n)continue;let s=new ImageData(n,t.width,t.height),o=document.createElement("canvas");o.width=t.width,o.height=t.height,o.getContext("2d").putImageData(s,0,0),i.push(o)}return i}async getScanSettings(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),P._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const i=JSON.parse(JSON.stringify(t));if(i.autoZoom||i.autoFocus||i.autoSuggestTip){if(!P._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return i.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(i.intervalTime,0),delete i.intervalTime),i.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=i.whenToPlaySoundforSuccessfulRead,delete i.whenToPlaySoundforSuccessfulRead),i.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=i.soundOnSuccessfullRead,delete i.soundOnSuccessfullRead),i.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=i.whenToVibrateforSuccessfulRead,delete i.whenToVibrateforSuccessfulRead),i.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=i.vibrateDuration,delete i.vibrateDuration),i.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=i.captureAndDecodeInParallel,delete i.captureAndDecodeInParallel),i.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=i.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=i.autoZoom,delete i.autoZoom),i.hasOwnProperty("autoFocus")&&(this.autoFocus=i.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete i.autoFocus),i.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=i.autoSuggestTip,delete i.autoFocus),await new Promise(((e,t)=>{let r=P._nextTaskID++;P._taskCallbackMap.set(r,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),P._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:i}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return P._onLog&&P._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));P._onLog&&P._onLog("======= once read ======="),P._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!P.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return P._onLog&&P._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:l}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),P.recalculateResultLocation(t,r,n,a,l,s,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(P._onLog&&P._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&this.beepSound&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),P._onLog&&P._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(P._onLog&&P._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else P._onLog&&P._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let n=0;n{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(P._onLog&&P._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=P._nextTaskID++;P._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),P._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}P._jsVersion="9.6.32",P._jsEditVersion="20231027",P._version=`loading...(JS ${P._jsVersion}.${P._jsEditVersion})`,P._license=g,P._sessionPassword=_,P.browserInfo=a,P._workerName=`dbr-${P._jsVersion}.browser.worker.js`,P._engineResourcePath=d,P._licenseServer=[],P._deviceFriendlyName="",P._isShowRelDecodeTimeInResults=!1,P._bWasmDebug=!1,P._bNeverShowDialog=!1,P.__bUseFullFeature=!0,P._nextTaskID=0,P._taskCallbackMap=new Map,P._pLoad=new C,P._lastErrorCode=0,P._lastErrorString="",P._setWarnnedEx=new Set,P._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var k={653:(e,t,i)=>{var r,n,s,o,a,l,h,c,u,d,f,g,_,p,m,v,y,S,b,w,C,x=x||{version:"5.2.1"};if(t.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.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;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function E(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function I(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,o);var l=new ImageData(a,r,n);i.putImageData(l,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.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"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:x.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}x.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof x.Gradient||this.set(t,new x.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof x.Pattern?i&&i():this.set(t,new x.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,l=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/l){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new x.Point(e.x-t.x,e.y-t.y),n=x.util.rotateVector(r,i);return new x.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=x.util.sin(t),r=x.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new x.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new x.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=x.util.createVector(e,t),n=x.util.createVector(e,i),s=x.util.calcAngleBetweenVectors(r,n),o=s*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,s),n)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,s=t.strokeUniform?new x.Point(1/t.scaleX,1/t.scaleY):new x.Point(1,1),o=function(e){var t=n/Math.hypot(e.x,e.y);return new x.Point(e.x*t*s.x,e.y*t*s.y)};return e.length<=1||e.forEach((function(a,l){var h,c,u=new x.Point(a.x,a.y);0===l?(c=e[l+1],h=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):l===e.length-1?(h=e[l-1],c=i?o(x.util.createVector(h,u)).addEquals(u):e[0]):(h=e[l-1],c=e[l+1]);var d,f,g=x.util.getBisector(u,h,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new x.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new x.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new x.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new x.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,s=!0,o=e.getImageData(t,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(e,t,i){for(var s=i[1],o=i[2],a=i[3],l=i[4],h=i[5],c=function(e,t,i,s,o,a,l){var h=Math.PI,c=l*h/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,b=m*v-m*y-v*S,w=0;if(b<0){var C=Math.sqrt(1-b/(m*v));i*=C,s*=C}else w=(o===a?-1:1)*Math.sqrt(b/(m*y+v*S));var T=w*i*p/s,E=-w*s*_/i,I=d*T-u*E+.5*e,O=u*T+d*E+.5*t,A=n(1,0,(_-T)/i,(p-E)/s),R=n((_-T)/i,(p-E)/s,(-_-T)/i,(-p-E)/s);0===a&&R>0?R-=2*h:1===a&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),M=[],F=R/D,L=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),P=A+F,k=0;kw)for(var T=1,E=_.length;T2;for(t=t||0,h&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,l=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+l*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,l){var h;if(x.cachesBoundsOfCurve&&(h=e.call(arguments),x.boundsOfCurveCache[h]))return x.boundsOfCurveCache[h];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,b=Math.abs,w=[],C=[[],[]];u=6*t-12*r+6*s,c=-3*t+9*r-9*s+3*a,d=3*r-3*t;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*l,d=3*n-3*i),b(c)<1e-12){if(b(u)<1e-12)continue;0<(f=-d/u)&&f<1&&w.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&w.push(g),0<(_=(-u-m)/(2*c))&&_<1&&w.push(_));for(var E,I,O,A=w.length,R=A;A--;)E=(O=1-(f=w[A]))*O*O*t+3*O*O*f*r+3*O*f*f*s+f*f*f*a,C[0][A]=E,I=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*l,C[1][A]=I;C[0][R]=t,C[1][R]=i,C[0][R+1]=a,C[1][R+1]=l;var D=[{x:y.apply(null,C[0]),y:y.apply(null,C[1])},{x:S.apply(null,C[0]),y:S.apply(null,C[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[h]=D),D},x.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=l(s),n=s,(r=o(h.x,h.y,i.x,i.y))+a>t?(s-=c,c/=2):(h=i,s+=c,a+=r);return i.angle=u(n),i}(s,t)}},x.util.transformPath=function(e,t,i){return i&&(t=x.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,s=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function s(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var l=0,h=o.length;l-1||"touch"===e.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),x.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,s=function(e){return n.call(e,0)};try{e=s(x.document.childNodes)instanceof Array}catch(e){}function o(e,t){var i=x.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=x.document.documentElement,n=x.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===x.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(s=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(e,t){var i=x.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=x.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},x.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},x.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},x.util.getById=function(e){return"string"==typeof e?x.document.getElementById(e):e},x.util.toArray=s,x.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},x.util.makeElement=o,x.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=o(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,s={left:0,top:0},o={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var h in l)o[l[h]]+=parseInt(t(e,h),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(s=e.getBoundingClientRect()),r=a(e),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(e){var t=x.jsdomImplForWrapper(e);return t._canvas||t._image},x.util.cleanUpJsdomNode=function(e){if(x.isLikelyNode){var t=x.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}x.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new x.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=e)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),s.open(r,t,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),x.log=console.log,x.warn=console.warn,function(){var e=x.util.object.extend,t=x.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}x.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var s=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(e){return x.window.setTimeout(e,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return s.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var s,o=!1,l=function(){var e=x.runningAnimations.indexOf(s);return e>-1&&x.runningAnimations.splice(e,1)[0]};return s=e(t(i),{cancel:function(){return o=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,h=e||+new Date,c=i.duration||500,u=h+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-h,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=b,s.durationRate=n,!o){if(!f(S,b,n))return t>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void l()):(d(S,b,n),void a(e));l()}}(h)})),s.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}x.util.animateColor=function(t,i,r,n){var s=new x.Color(t).getSource(),o=new x.Color(i).getSource(),a=n.onComplete,l=n.onChange;return n=n||{},x.util.animate(x.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(t,i,r,s){return e(i,r,n.colorEasing?n.colorEasing(t,s):1-Math.cos(t/s*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(o,o,0),i,r)},onChange:function(t,i,r){if(l){if(Array.isArray(t))return l(e(t,t,0),i,r);l(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=l?i.map(s):s(i,n)}}else i="";return!l&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,s,o=[];for(n=0,s=t.length;n1;)l.shift(),h=t.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,o,a,l,h=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,b={},w="",C=0,x=0;if(b.width=0,b.height=0,b.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") ",a=(e.getAttribute("transform")||"")+w,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return b;if(m)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(h[1]),r=-parseFloat(h[2]),n=parseFloat(h[3]),o=parseFloat(h[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,y?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.height/o),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),C=b.width-n*c,x=b.height-o*c,"Mid"===p.alignX&&(C/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(C=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+x)+") ","svg"===e.nodeName){for(l=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l)}else(l=e).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),b}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,s){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,s){var o,a=(s.x-n.x)*(e.y-n.y)-(s.y-n.y)*(e.x-n.x),l=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),h=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==h){var c=a/h,u=l/h;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):o=new i}else o=new i(0===a||0===l?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,l=new i,h=r.length;for(a=0;a0&&(l.status="Intersection"),l},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,s=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var s=r.min(n),o=r.max(n),a=new t.Point(o.x,s.y),l=new t.Point(s.x,o.y),h=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,l,e),d=i.intersectLinePolygon(l,s,e),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,s,o,a=t.util.array.max([e,i,r]),l=t.util.array.min([e,i,r]);if(o=(a+l)/2,a===l)n=s=0;else{var h=a-l;switch(s=o>.5?h/(2-a-l):h/(a+l),a){case e:n=(i-r)/h+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,s=t.util.object.clone(i);s.target=r,n&&n.fire("object:"+e,s),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===h&&e.originY===h}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),l=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),l}}function S(e,t){return function(i,r,n,s){var o=t(i,r,n,s);return o&&g(e,v(i,r,n,s)),o}}function b(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],l=o.canvas.getZoom(),h=o.padding/l,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(e){return e.flipX!==e.flipY}function C(e,t,i,r,n){if(0!==e[t]){var s=n/e._getTransformedDimensions()[r]*e[i];e.set(i,s)}}function x(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(0,h.skewY),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?n=0:(n=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().y;h.set("skewX",n),C(h,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(h.skewX,0),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?n=0:(n=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().x;h.set("skewY",n),C(h,"skewX","scaleX","x",p)}return _}function E(e,t,i,r,n){n=n||{};var s,o,a,l,h,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),w=m(f,y,S),C=t.gestureScale;if(w)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=b(t,t.originX,t.originY,i,r),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=h),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==h||t.signY!==u))return!1;if(l=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,E=x/(Math.abs(l.x*T.scaleX/f.scaleX)+Math.abs(l.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}else o=Math.abs(s.x*f.scaleX/l.x),a=Math.abs(s.y*f.scaleY/l.y);p(t)&&(o*=2,a*=2),t.signX!==h&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=h),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var I=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)),I!==f.scaleX||O!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),s="";if(0!==t.x&&0===t.y?s="x":0===t.x&&0!==t.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,t);return i[o]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var s=f(i,t)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,l=Math.atan2(n.ey-o.y,n.ex-o.x),h=Math.atan2(r-o.y,i-o.x),c=u(h-l+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),w(l)&&(n=n===s?a:s)),t.originX=n,S("skewing",y(x))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=b(t,h,h,i,r).y>0?o:l:(c>0&&(n=u===s?o:l),c<0&&(n=u===s?l:o),w(a)&&(n=n===o?l:o)),t.originY=n,S("skewing",y(T))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,s=i-t.offsetX,o=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==s,l=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),l&&n.set("top",o),(a||l)&&g("moving",v(e,t,i,r)),a||l},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=b,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,e.scale(1,a/o),d=i*o/a):a>o?(s=a,e.scale(o/a,1),u=t*a/o):s=o,e.lineWidth=1,e.beginPath(),e.arc(u,d,s/2,0,2*Math.PI,!1),e[h](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||s.cornerColor,e.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(s.angle)),e[h+"Rect"](-u,-d,o,a),c&&e.strokeRect(-u,-d,o,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.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(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,s){var o,a,l,h,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);o=f*t.util.cos(g),a=f*t.util.sin(g),l=f*t.util.cos(_),h=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=l=f*t.util.cos(g),a=h=f*t.util.sin(g);return{tl:{x:r-h,y:n-l},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+h,y:n+l}}},render:function(e,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,s):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,s)}}}(t),function(){function e(e,t){var i,r,n,s,o=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var l=o.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new x.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={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 x.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,s,o,a=t(this.coords,!0),l=(i=i||{},t(this.colorStops,!0)),h=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),r=0,n=l.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=l.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(e){var t,i,r,n=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,l,h,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(o="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(o="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),l=c.length;l--;)f.push(e(c[l],s));return h=x.parseTransformAttribute(d),function(e,t,i,r){var n,s;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?s=1:"-Infinity"===n?s=0:(s=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(s*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(s*=i.viewBoxHeight||i.height)))),t[e]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:t.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:h,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=x.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,s=this.offsetY/e.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?o=t.src:t.toDataURL&&(o=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,s=t.Object.NUM_FRACTION_DIGITS,o=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(o.x)+this.blur)/e.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/e.height,s)+20),e.flipX&&(o.x*=-1),e.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var e=x.util.object.extend,t=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,n=x.util.transformPoint,s=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=x.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?x.util.loadImage(t,(function(t,n){if(t){var s=new x.Image(t,r);this[e]=s,s.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw l;if(e.style||(e.style={}),void 0===e.getContext)throw l;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=x.util.getById(e)||this._createCanvasElement(),x.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(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,s=t.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;t.viewBox?o='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("