diff --git a/API Reference.url b/API Reference.url index b3a5e549..bc2b1b86 100644 --- a/API Reference.url +++ b/API Reference.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=10.2.10 \ No newline at end of file +URL=https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=10.2.1000 \ No newline at end of file diff --git a/LEGAL.txt b/LEGAL.txt index 7fea86c8..00ec6130 100644 --- a/LEGAL.txt +++ b/LEGAL.txt @@ -9,7 +9,7 @@ This SDK contains parts of following softwares which are used under license. =================================================================================== Zlib. -Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + (C) 1995-2022 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -27,8 +27,8 @@ Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. - Jean-loup Gailly - Mark Adler + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu =================================================================================== diff --git a/LICENSE b/LICENSE index 6cce8bcf..e7349294 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ Copyright © 2003–2024 Dynamsoft. All Rights Reserved. The use of this software is governed by the Dynamsoft Terms and Conditions. -https://www.dynamsoft.com/barcode-reader/license-agreement/#javascript \ No newline at end of file +URL=https://www.dynamsoft.com/barcode-reader/license-agreement/#javascript \ No newline at end of file diff --git a/README.md b/README.md index 6dcc2656..8c9d855f 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ In this guide, you will learn step by step on how to integrate the DBR-JS SDK in **Popular Examples** - Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.2.10&utm_source=github) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/angular/dist/hello-world/?ver=10.2.10&utm_source=github) +- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/angular/dist/angular/?ver=10.2.10&utm_source=github) - React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/react/build/?ver=10.2.10&utm_source=github) - Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/vue) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/vue/dist/?ver=10.2.10&utm_source=github) - PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.2.10&utm_source=github) @@ -89,20 +89,20 @@ The complete code of the "Hello World" example is shown below
- + @@ -148,26 +148,26 @@ The complete code of the "Hello World" example is shown below - `Dynamsoft.Core.CoreModule.loadWasm(["dbr"])`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `router` which controls the entire process in three steps: +- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - **Retrieve Images from the Image Source** - - `router` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. + - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. ```js - router.setInput(cameraEnhancer); + cvRouter.setInput(cameraEnhancer); ``` > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(view)` - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `router` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. + - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. ```js - router.startCapturing("ReadSingleBarcode"); + cvRouter.startCapturing("ReadSingleBarcode"); ``` - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `router` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). + - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). ```js - router.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); + cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `router` via the method `addResultFilter()`. + - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. ```js - router.addResultFilter(filter); + cvRouter.addResultFilter(filter); ``` > Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). @@ -208,7 +208,19 @@ To utilize the SDK, the initial step involves including the corresponding resour * `cvr.js` introduces the `CaptureVisionRouter` class, which governs the entire image processing workflow. * `dce.js` comprises classes that offer camera support and basic user interface functionalities. -For simplification, starting from version 10.2.10, we introduced `dbr.bundle.js`. Including this file is equivalent to incorporating all six packages. +For simplification, starting from version 10.0.21, we introduced `dbr.bundle.js`. Including this file is equivalent to incorporating all six packages. + +* dynamsoft-core@3.2.30/dist/core.js +* dynamsoft-license@3.2.21/dist/license.js +* dynamsoft-utility@1.2.20/dist/utility.js +* dynamsoft-barcode-reader@10.2.10/dist/dbr.js +* dynamsoft-capture-vision-router@2.2.30/dist/cvr.js +* dynamsoft-camera-enhancer@4.0.3/dist/dce.js + +Equivalent to +* dynamsoft-barcode-reader-bundle@10.2.1000/dist/dbr.bundle.js + +In the following chapters, we will use `dbr.bundle.js`. #### Use a public CDN @@ -217,48 +229,22 @@ The simplest way to include the SDK is to use either the [jsDelivr](https://jsde - jsDelivr ```html - - - - - - + ``` - Or just +- UNPKG ```html - + ``` -- UNPKG +- In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. ```html - - - - - - + ``` - Or just - - ```html - - ``` - -In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. - -- https://download2.dynamsoft.com/packages/dynamsoft-core@3.2.10/dist/core.js -- https://download2.dynamsoft.com/packages/dynamsoft-license@3.2.10/dist/license.js -- https://download2.dynamsoft.com/packages/dynamsoft-utility@1.2.10/dist/utility.js -- https://download2.dynamsoft.com/packages/dynamsoft-barcode-reader@10.2.10/dist/dbr.js -- https://download2.dynamsoft.com/packages/dynamsoft-capture-vision-router@2.2.10/dist/cvr.js -- https://download2.dynamsoft.com/packages/dynamsoft-camera-enhancer@4.0.2/dist/dce.js -- or bundle: https://download2.dynamsoft.com/packages/dynamsoft-barcode-reader@10.2.10/dist/dbr.bundle.js - -However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. + However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. #### Host the SDK yourself (optional) @@ -270,30 +256,20 @@ Options to download the SDK: [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.2.10&utm_source=github&product=dbr&package=js) -- yarn +- npm ```cmd - yarn add dynamsoft-core@3.2.10 --save - yarn add dynamsoft-license@3.2.10 --save - yarn add dynamsoft-utility@1.2.10 --save - yarn add dynamsoft-barcode-reader@10.2.10 --save - yarn add dynamsoft-capture-vision-router@2.2.10 --save - yarn add dynamsoft-camera-enhancer@4.0.2 --save - yarn add dynamsoft-capture-vision-std@1.2.0 --save - yarn add dynamsoft-image-processing@2.2.10 --save + npm i dynamsoft-barcode-reader-bundle@10.2.1000 -E + npm i dynamsoft-capture-vision-std@1.2.0 -E + npm i dynamsoft-image-processing@2.2.10 -E ``` -- npm +- yarn ```cmd - npm install dynamsoft-core@3.2.10 --save - npm install dynamsoft-license@3.2.10 --save - npm install dynamsoft-utility@1.2.10 --save - npm install dynamsoft-barcode-reader@10.2.10 --save - npm install dynamsoft-capture-vision-router@2.2.10 --save - npm install dynamsoft-camera-enhancer@4.0.2 --save - npm install dynamsoft-capture-vision-std@1.2.0 --save - npm install dynamsoft-image-processing@2.2.10 --save + yarn add dynamsoft-barcode-reader-bundle@10.2.1000 -E + yarn add dynamsoft-capture-vision-std@1.2.0 -E + yarn add dynamsoft-image-processing@2.2.10 -E ``` Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this @@ -301,35 +277,13 @@ Depending on how you downloaded the SDK and how you intend to use it, you can ty - From the website ```html - - - - - - - ``` - - Or just - - ```html - + ``` - yarn or npm ```html - - - - - - - ``` - - Or just - - ```html - + ``` *Note*: @@ -402,9 +356,9 @@ To use the SDK, we first create a `CaptureVisionRouter` object. ```javascript Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -let router = null; +let cvRouter = null; try { - router = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); + cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); } catch (ex) { console.error(ex); } @@ -417,12 +371,12 @@ When creating a `CaptureVisionRouter` object within a function which may be call ```javascript Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -let pRouter = null; // promise of router -let router = null; +let pCvRouter = null; // promise of cvRouter +let cvRouter = null; document.getElementById('btn-scan').addEventListener('click', async () => { try { - router = await (pRouter = pRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); + cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); } catch (ex) { console.error(ex); } @@ -431,7 +385,7 @@ document.getElementById('btn-scan').addEventListener('click', async () => { #### Connect an image source -The `CaptureVisionRouter` object, denoted as `router`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `router`. +The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. To enable video streaming on the webpage, we create a `CameraView` object referred to as `view`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. @@ -443,7 +397,7 @@ To enable video streaming on the webpage, we create a `CameraView` object referr let view = await Dynamsoft.DCE.CameraView.createInstance(); let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(view); document.querySelector("#cameraViewContainer").append(view.getUIElement()); -router.setInput(cameraEnhancer); +cvRouter.setInput(cameraEnhancer); ``` #### Register a result receiver @@ -457,23 +411,23 @@ resultReceiver.onDecodedBarcodesReceived = (result) => { if (result.barcodeResultItems.length > 0) { resultsContainer.textContent = ''; for (let item of result.barcodeResultItems) { - // In this example, the barcode result is shown on the page beneath the video + // In this example, the barcode results are displayed on the page below the video. resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; } } }; -router.addResultReceiver(resultReceiver); +cvRouter.addResultReceiver(resultReceiver); ``` You can also write code like this. It is the same. ```javascript const resultsContainer = document.querySelector("#results"); -router.addResultReceiver({ onDecodedBarcodesReceived: (result) => { +cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { if (result.barcodeResultItems.length > 0) { resultsContainer.textContent = ''; for (let item of result.barcodeResultItems) { - // In this example, the barcode result is shown on the page beneath the video + // In this example, the barcode results are displayed on the page below the video. resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; } } @@ -486,17 +440,17 @@ Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs With the setup now complete, we can proceed to process the images in two straightforward steps: -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `router` as per its request. +1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. 2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. ```javascript await cameraEnhancer.open(); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` *Note*: -* `router` is engineered to consistently request images from the image source. +* `cvRouter` is engineered to consistently request images from the image source. * Various preset templates are at your disposal for barcode reading: | Template Name | Function Description | @@ -522,11 +476,11 @@ When making adjustments to some basic tasks, we often only need to modify [Simpl The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. ```javascript -let settings = await router.getSimplifiedSettings("ReadSingleBarcode"); +let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); settings.barcodeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await router.updateSettings("ReadSingleBarcode", settings); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.updateSettings("ReadSingleBarcode", settings); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html). @@ -536,36 +490,33 @@ For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSet Additionally, we have the option to modify the template to retrieve the original image containing the barcode. ```javascript -let settings = await router.getSimplifiedSettings("ReadSingleBarcode"); +let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); settings.capturedResultItemTypes |= Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await router.updateSettings("ReadSingleBarcode", settings); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.updateSettings("ReadSingleBarcode", settings); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. ```javascript -let settings = await router.getSimplifiedSettings("ReadSingleBarcode"); +let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); settings.capturedResultItemTypes = Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await router.updateSettings("ReadSingleBarcode", settings); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.updateSettings("ReadSingleBarcode", settings); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: ```javascript +const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; resultReceiver.onCapturedResultReceived = (result) => { - let barcodes = result.items.filter((item) => - item.type === Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE - ); + let barcodes = result.items.filter(item => item.type === EnumCRIT.CRIT_BARCODE); if (barcodes.length > 0) { let image = result.items.filter( - (item) => - item.type === - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE + item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE )[0].imageData; // The image that we found the barcode(s) on. } @@ -579,10 +530,10 @@ The SDK is initially configured to process images sequentially without any break > Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. ```javascript -let settings = await router.getSimplifiedSettings("ReadSingleBarcode"); +let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); settings.minImageCaptureInterval = 500; -await router.updateSettings("ReadSingleBarcode", settings); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.updateSettings("ReadSingleBarcode", settings); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` ##### Specify a scan region @@ -590,7 +541,7 @@ await router.startCapturing("ReadSingleBarcode"); You can use the parameter `roi` (region of interest) together with the parameter `roiMeasuredInPercentage` to configure the SDK to only read a specific region on the image frames. For example, the following code limits the reading in the center 25%( = 50% * 50%) of the image frames: ```javascript -let settings = await router.getSimplifiedSettings("ReadSingleBarcode"); +let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); settings.roiMeasuredInPercentage = true; settings.roi.points = [ { x: 25, y: 25 }, @@ -598,8 +549,8 @@ settings.roi.points = [ { x: 75, y: 75 }, { x: 25, y: 75 }, ]; -await router.updateSettings("ReadSingleBarcode", settings); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.updateSettings("ReadSingleBarcode", settings); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` While the code above accomplishes the task, a more effective approach is to restrict the scan region directly at the image source, as demonstrated in the following code snippet. @@ -627,10 +578,10 @@ You can set the maximum time allowed for processing a single image with the prop > Please be aware that the SDK will cease processing an image if its processing time exceeds the duration specified by the `timeout` parameter. It should not be confused with the previously discussed parameter, `minImageCaptureInterval`. ```javascript -let settings = await router.getSimplifiedSettings("ReadSingleBarcode"); +let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); settings.timeout = 500; -await router.updateSettings("ReadSingleBarcode", settings); -await router.startCapturing("ReadSingleBarcode"); +await cvRouter.updateSettings("ReadSingleBarcode", settings); +await cvRouter.startCapturing("ReadSingleBarcode"); ``` --> @@ -643,8 +594,8 @@ The preset templates have a lot more settings that can be customized to best sui Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. ```javascript -await router.initSettings("PATH-TO-THE-FILE"); //e.g. "https://your-website/ReadSingleBarcode.json") -await router.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the +await cvRouter.initSettings("PATH-TO-THE-FILE"); //e.g. "https://your-website/ReadSingleBarcode.json") +await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the json file. ``` #### Filter the results (Important) @@ -656,7 +607,7 @@ While processing video frames, it's common for the same barcode to be detected m ```js let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); filter.enableResultCrossVerification("barcode", true); -await router.addResultFilter(filter); +await cvRouter.addResultFilter(filter); ``` *Note*: @@ -668,7 +619,7 @@ await router.addResultFilter(filter); ```js let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); filter.enableResultDeduplication("barcode", true); -await router.addResultFilter(filter); +await cvRouter.addResultFilter(filter); ``` *Note*: @@ -684,7 +635,7 @@ Under certain circumstances, this duration can be extended with the method `setD ```js let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await router.addResultFilter(filter); +await cvRouter.addResultFilter(filter); ``` You can also enable both options at the same time: @@ -694,7 +645,7 @@ let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); filter.enableResultCrossVerification("barcode", true); filter.enableResultDeduplication("barcode", true); filter.setDuplicateForgetTime(5000); -await router.addResultFilter(filter); +await cvRouter.addResultFilter(filter); ``` #### Add feedback @@ -710,7 +661,7 @@ resultReceiver.onDecodedBarcodesReceived = (result) => { Dynamsoft.DCE.Feedback.beep(); } }; -router.addResultReceiver(resultReceiver); +cvRouter.addResultReceiver(resultReceiver); ``` ### Customize the UI diff --git a/dist/DBR-PresetTemplates.json b/dist/DBR-PresetTemplates.json deleted file mode 100644 index 08093841..00000000 --- a/dist/DBR-PresetTemplates.json +++ /dev/null @@ -1,625 +0,0 @@ -{ - "CaptureVisionTemplates": [ - { - "Name": "Default" - }, - { - "Name": "ReadBarcodes_Default", - "ImageROIProcessingNameArray": [ - "roi-read-barcodes" - ], - "Timeout": 10000 - }, - { - "Name": "ReadBarcodes_SpeedFirst", - "ImageROIProcessingNameArray": [ - "roi-read-barcodes-speed-first" - ], - "Timeout": 10000 - }, - { - "Name": "ReadBarcodes_ReadRateFirst", - "ImageROIProcessingNameArray": [ - "roi-read-barcodes-read-rate" - ], - "Timeout": 100000 - }, - { - "Name": "ReadSingleBarcode", - "ImageROIProcessingNameArray": [ - "roi-read-single-barcode" - ], - "Timeout": 10000 - }, - { - "Name": "ReadBarcodes_Balance", - "ImageROIProcessingNameArray": [ - "roi-read-barcodes-balance" - ], - "Timeout": 100000 - }, - { - "Name": "ReadDenseBarcodes", - "ImageROIProcessingNameArray": [ - "roi-read-barcodes-dense" - ], - "Timeout": 10000 - }, - { - "Name": "ReadDistantBarcodes", - "ImageROIProcessingNameArray": [ - "roi-read-barcodes-distant" - ], - "Timeout": 10000 - } - ], - "TargetROIDefOptions": [ - { - "Name": "roi-read-barcodes", - "TaskSettingNameArray": [ - "task-read-barcodes" - ] - }, - { - "Name": "roi-read-barcodes-speed-first", - "TaskSettingNameArray": [ - "task-read-barcodes-speed-first" - ] - }, - { - "Name": "roi-read-barcodes-read-rate", - "TaskSettingNameArray": [ - "task-read-barcodes-read-rate" - ] - }, - { - "Name": "roi-read-single-barcode", - "TaskSettingNameArray": [ - "task-read-single-barcode" - ] - }, - { - "Name": "roi-read-barcodes-balance", - "TaskSettingNameArray": [ - "task-read-barcodes-balance" - ] - }, - { - "Name": "roi-read-barcodes-dense", - "TaskSettingNameArray": [ - "task-read-barcodes-dense" - ] - }, - { - "Name": "roi-read-barcodes-distant", - "TaskSettingNameArray": [ - "task-read-barcodes-distant" - ] - } - ], - "BarcodeFormatSpecificationOptions": [ - { - "Name": "bfs1", - "BarcodeFormatIds": [ - "BF_PDF417", - "BF_QR_CODE", - "BF_DATAMATRIX", - "BF_AZTEC", - "BF_MICRO_QR", - "BF_MICRO_PDF417", - "BF_DOTCODE" - ], - "MirrorMode": "MM_BOTH" - }, - { - "Name": "bfs2", - "BarcodeFormatIds": [ - "BF_ALL" - ], - "MirrorMode": "MM_NORMAL" - }, - { - "Name": "bfs1-speed-first", - "BaseBarcodeFormatSpecification": "bfs1" - }, - { - "Name": "bfs2-speed-first", - "BaseBarcodeFormatSpecification": "bfs2" - }, - { - "Name": "bfs1-read-rate-first", - "BaseBarcodeFormatSpecification": "bfs1" - }, - { - "Name": "bfs2-read-rate-first", - "BaseBarcodeFormatSpecification": "bfs2" - }, - { - "Name": "bfs1-single-barcode", - "BaseBarcodeFormatSpecification": "bfs1" - }, - { - "Name": "bfs2-single-barcode", - "BaseBarcodeFormatSpecification": "bfs2" - }, - { - "Name": "bfs1-balance", - "BaseBarcodeFormatSpecification": "bfs1" - }, - { - "Name": "bfs2-balance", - "BaseBarcodeFormatSpecification": "bfs2" - }, - { - "Name": "bfs1-dense", - "BaseBarcodeFormatSpecification": "bfs1" - }, - { - "Name": "bfs2-dense", - "BaseBarcodeFormatSpecification": "bfs2" - }, - { - "Name": "bfs1-distant", - "BaseBarcodeFormatSpecification": "bfs1" - }, - { - "Name": "bfs2-distant", - "BaseBarcodeFormatSpecification": "bfs2" - } - ], - "BarcodeReaderTaskSettingOptions": [ - { - "Name": "task-read-barcodes", - "ExpectedBarcodesCount" : 1, - "LocalizationModes": [ - { - "Mode": "LM_SCAN_DIRECTLY", - "ScanDirection": 2 - }, - { - "Mode": "LM_CONNECTED_BLOCKS" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1", - "bfs2" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-barcodes" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-barcodes" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-barcodes" - } - ] - }, - { - "Name": "task-read-barcodes-speed-first", - "ExpectedBarcodesCount": 0, - "BarcodeFormatIds" : [ "BF_DEFAULT" ], - "LocalizationModes": [ - { - "Mode": "LM_SCAN_DIRECTLY", - "ScanDirection": 2 - }, - { - "Mode": "LM_CONNECTED_BLOCKS" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1-speed-first", - "bfs2-speed-first" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-barcodes-speed-first" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-barcodes-speed-first" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-barcodes-speed-first" - } - ] - }, - { - "Name": "task-read-barcodes-read-rate", - "ExpectedBarcodesCount" : 999, - "LocalizationModes": [ - { - "Mode": "LM_CONNECTED_BLOCKS" - }, - { - "Mode": "LM_LINES" - }, - { - "Mode": "LM_STATISTICS" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - }, - { - "Mode": "DM_DIRECT_BINARIZATION" - }, - { - "Mode": "DM_SMOOTHING" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1-read-rate-first", - "bfs2-read-rate-first" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-barcodes-read-rate" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-barcodes-read-rate" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-barcodes-read-rate" - } - ] - }, - { - "Name": "task-read-single-barcode", - "ExpectedBarcodesCount": 1, - "LocalizationModes": [ - { - "Mode": "LM_SCAN_DIRECTLY", - "ScanDirection": 2 - }, - { - "Mode": "LM_CONNECTED_BLOCKS" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1-single-barcode", - "bfs2-single-barcode" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-single-barcode" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-single-barcode" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-single-barcode" - } - ] - }, - { - "Name": "task-read-barcodes-balance", - "ExpectedBarcodesCount" : 999, - "LocalizationModes": [ - { - "Mode": "LM_CONNECTED_BLOCKS" - }, - { - "Mode": "LM_SCAN_DIRECTLY" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - }, - { - "Mode": "DM_DIRECT_BINARIZATION" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1-balance", - "bfs2-balance" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-barcodes-balance" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-barcodes-balance" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-barcodes-balance" - } - ] - }, - { - "Name": "task-read-barcodes-dense", - "ExpectedBarcodesCount" : 0, - "LocalizationModes": [ - { - "Mode": "LM_CONNECTED_BLOCKS" - }, - { - "Mode": "LM_LINES" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - }, - { - "Mode": "DM_DIRECT_BINARIZATION" - }, - { - "Mode": "DM_SMOOTHING" - }, - { - "Mode": "DM_GRAY_EQUALIZATION" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1-dense", - "bfs2-dense" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-barcodes-dense" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-barcodes-dense" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-barcodes-dense" - } - ] - }, - { - "Name": "task-read-barcodes-distant", - "ExpectedBarcodesCount" : 0, - "LocalizationModes": [ - { - "Mode": "LM_CONNECTED_BLOCKS" - }, - { - "Mode": "LM_LINES" - } - ], - "DeblurModes": [ - { - "Mode": "DM_BASED_ON_LOC_BIN" - }, - { - "Mode": "DM_THRESHOLD_BINARIZATION" - }, - { - "Mode": "DM_DIRECT_BINARIZATION" - } - ], - "BarcodeFormatSpecificationNameArray": [ - "bfs1-distant", - "bfs2-distant" - ], - "SectionImageParameterArray": [ - { - "Section": "ST_REGION_PREDETECTION", - "ImageParameterName": "ip-read-barcodes-distant" - }, - { - "Section": "ST_BARCODE_LOCALIZATION", - "ImageParameterName": "ip-read-barcodes-distant" - }, - { - "Section": "ST_BARCODE_DECODING", - "ImageParameterName": "ip-read-barcodes-distant" - } - ] - } - ], - "ImageParameterOptions": [ - { - "Name": "ip-read-barcodes", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 71, - "BlockSizeY": 71, - "EnableFillBinaryVacancy": 0 - } - ], - "GrayscaleTransformationModes" : [ - { - "Mode": "GTM_ORIGINAL" - } - ] - }, - { - "Name": "ip-read-barcodes-speed-first", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 71, - "BlockSizeY": 71, - "EnableFillBinaryVacancy": 0 - } - ], - "GrayscaleTransformationModes": [ - { - "Mode": "GTM_ORIGINAL" - } - ] - }, - { - "Name": "ip-read-barcodes-read-rate", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 0, - "BlockSizeY": 0, - "EnableFillBinaryVacancy": 1 - } - ], - "GrayscaleTransformationModes" : [ - { - "Mode": "GTM_ORIGINAL" - } - ], - "ScaleDownThreshold" : 100000 - }, - { - "Name": "ip-read-single-barcode", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 71, - "BlockSizeY": 71, - "EnableFillBinaryVacancy": 0 - } - ], - "GrayscaleTransformationModes": [ - { - "Mode": "GTM_ORIGINAL" - } - ] - }, - { - "Name": "ip-read-barcodes-balance", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 0, - "BlockSizeY": 0, - "EnableFillBinaryVacancy": 1 - } - ], - "GrayscaleTransformationModes" : [ - { - "Mode": "GTM_ORIGINAL" - } - ] - }, - { - "Name": "ip-read-barcodes-dense", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 0, - "BlockSizeY": 0, - "EnableFillBinaryVacancy": 1 - } - ], - "GrayscaleTransformationModes" : [ - { - "Mode": "GTM_ORIGINAL" - } - ], - "ScaleDownThreshold" : 100000 - }, - { - "Name": "ip-read-barcodes-distant", - "TextDetectionMode": { - "Mode": "TTDM_LINE", - "Direction": "UNKNOWN", - "Sensitivity": 3 - }, - "IfEraseTextZone": 1, - "BinarizationModes": [ - { - "Mode": "BM_LOCAL_BLOCK", - "BlockSizeX": 0, - "BlockSizeY": 0, - "EnableFillBinaryVacancy": 1 - } - ], - "GrayscaleTransformationModes" : [ - { - "Mode": "GTM_ORIGINAL" - } - ], - "ScaleDownThreshold" : 2300 - } - ] -} \ No newline at end of file diff --git a/dist/dbr.bundle.d.ts b/dist/dbr.bundle.d.ts new file mode 100644 index 00000000..1c54afb8 --- /dev/null +++ b/dist/dbr.bundle.d.ts @@ -0,0 +1,12 @@ +import * as dynamsoftCore from 'dynamsoft-core'; +export { dynamsoftCore as Core }; +import * as dynamsoftLicense from 'dynamsoft-license'; +export { dynamsoftLicense as License }; +import * as dynamsoftCaptureVisionRouter from 'dynamsoft-capture-vision-router'; +export { dynamsoftCaptureVisionRouter as CVR }; +import * as dynamsoftCameraEnhancer from 'dynamsoft-camera-enhancer'; +export { dynamsoftCameraEnhancer as DCE }; +import * as dynamsoftBarcodeReader from 'dynamsoft-barcode-reader'; +export { dynamsoftBarcodeReader as DBR }; +import * as dynamsoftUtility from 'dynamsoft-utility'; +export { dynamsoftUtility as Utility }; diff --git a/dist/dbr.bundle.esm.d.ts b/dist/dbr.bundle.esm.d.ts new file mode 100644 index 00000000..bbfbd479 --- /dev/null +++ b/dist/dbr.bundle.esm.d.ts @@ -0,0 +1,6 @@ +export * from 'dynamsoft-core'; +export * from 'dynamsoft-license'; +export * from 'dynamsoft-capture-vision-router'; +export * from 'dynamsoft-camera-enhancer'; +export * from 'dynamsoft-barcode-reader'; +export * from 'dynamsoft-utility'; diff --git a/dist/dbr.bundle.js b/dist/dbr.bundle.js index cbbaa9cb..bbdba9d5 100644 --- a/dist/dbr.bundle.js +++ b/dist/dbr.bundle.js @@ -1,61 +1,11 @@ /*! * Dynamsoft JavaScript Library -* @product Dynamsoft Barcode Reader JS Edition +* @product Dynamsoft Barcode Reader JS Edition Bundle * @website http://www.dynamsoft.com * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft -* @version 10.2.10 +* @version 10.2.1000 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft={})}(this,(function(t){"use strict"; -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Core JS Edition - * @website https://www.dynamsoft.com - * @copyright Copyright 2024, Dynamsoft Corporation - * @author Dynamsoft - * @version 3.2.10 - * @fileoverview Dynamsoft JavaScript Library for Core - * More info on Dynamsoft Core JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module.html - */function e(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function i(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var r,n,s;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(r||(r={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(n||(n={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(s||(s={}));const o=t=>Object.prototype.toString.call(t),a=t=>Array.isArray?Array.isArray(t):"[object Array]"===o(t),h=t=>"[object Boolean]"===o(t),l=t=>"number"==typeof t&&!Number.isNaN(t),c=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),u=t=>!(!c(t)||!(t.bytes instanceof Uint8Array)||!l(t.width)||t.width<=0||!l(t.height)||t.height<=0||!l(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!f(t.tag)),d=t=>!(!c(t)||!l(t.left)||t.left<0||!l(t.top)||t.top<0||!l(t.right)||t.right<0||!l(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!h(t.isMeasuredInPercentage)),f=t=>!!c(t)&&!!l(t.imageId)&&"type"in t,g=t=>!(!c(t)||!m(t.startPoint)||!m(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),m=t=>!!c(t)&&!!l(t.x)&&!!l(t.y),p=t=>!!c(t)&&!!a(t.points)&&0!=t.points.length&&!t.points.some((t=>!m(t))),_=t=>!!c(t)&&!!a(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!m(t))),v=t=>!(!c(t)||!l(t.x)||!l(t.y)||!l(t.width)||t.width<0||!l(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!h(t.isMeasuredInPercentage));async function y(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}const w=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t=e(this,b,"f"))switch(e(this,S,"f")){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:if(e(this,T,"f").push(t),c(e(this,x,"f"))&&l(e(this,x,"f").imageId)&&1==e(this,x,"f").keepInBuffer)for(;e(this,T,"f").length>e(this,b,"f");){const t=e(this,T,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)!==e(this,x,"f").imageId}));e(this,T,"f").splice(t,1)}else e(this,T,"f").splice(0,e(this,T,"f").length-e(this,b,"f"))}else e(this,T,"f").push(t)}getImage(){if(0===e(this,T,"f").length)return null;let t;if(e(this,x,"f")&&l(e(this,x,"f").imageId)){const i=e(this,C,"m",R).call(this,e(this,x,"f").imageId);if(i<0)throw new Error(`Image with id ${e(this,x,"f").imageId} doesn't exist.`);t=e(this,T,"f").slice(i,i+1)[0]}else t=e(this,T,"f").pop();if([s.IPF_RGB_565,s.IPF_RGB_555,s.IPF_RGB_888,s.IPF_ARGB_8888,s.IPF_RGB_161616,s.IPF_ARGB_16161616,s.IPF_ABGR_8888,s.IPF_ABGR_16161616,s.IPF_BGR_888].includes(t.format)){if(e(this,A,"f")===n.CCUT_RGB_R_CHANNEL_ONLY){O._onLog&&O._onLog("only get R channel data.");const e=new Uint8Array(t.width*t.height);for(let i=0;i0!==t.length&&t.every((t=>l(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!h(e))throw new TypeError("Invalid 'keepInBuffer'.");i(this,x,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){i(this,x,null,"f")}hasImage(t){return e(this,C,"m",R).call(this,t)>=0}startFetching(){i(this,I,!0,"f")}stopFetching(){i(this,I,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(i(this,b,t,"f");e(this,T,"f")&&e(this,T,"f").length>t;)e(this,T,"f").shift()}getMaxImageCount(){return e(this,b,"f")}getImageCount(){return e(this,T,"f").length}clearBuffer(){e(this,T,"f").length=0}isBufferEmpty(){return 0===e(this,T,"f").length}setBufferOverflowProtectionMode(t){i(this,S,t,"f")}getBufferOverflowProtectionMode(){return e(this,S,"f")}setColourChannelUsageType(t){i(this,A,t,"f")}getColourChannelUsageType(){return e(this,A,"f")}}T=new WeakMap,b=new WeakMap,S=new WeakMap,I=new WeakMap,x=new WeakMap,A=new WeakMap,C=new WeakSet,R=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return e(this,T,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))};const D="undefined"==typeof self,L=(()=>{if(!D&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),M=t=>{if(null==t&&(t="./"),D);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};let F,P,k,B,N;"undefined"!=typeof navigator&&(F=navigator,P=F.userAgent,k=F.platform,B=F.mediaDevices),function(){if(!D){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:F.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:k,search:"Win"},Mac:{str:k},Linux:{str:k}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||P,o=n.search||e,a=n.verStr||P,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||P,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=P.indexOf("Windows NT")&&(n="HarmonyOS"),N={browser:i,version:r,OS:n}}D&&(N={browser:"ssr",version:0,OS:"ssr"})}();const U="undefined"!=typeof WebAssembly&&P&&!(/Safari/.test(P)&&!/Chrome/.test(P)&&/\(.+\s11_2_([2-6]).*\)/.test(P)),j=!("undefined"==typeof Worker),G=!(!B||!B.getUserMedia),W=async()=>{let t=!1;if(G)try{(await B.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===N.browser&&N.version>66||"Safari"===N.browser&&N.version>13||"OPR"===N.browser&&N.version>43||"Edge"===N.browser&&N.version;const V=t=>t&&"object"==typeof t&&"function"==typeof t.then;class Y extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(V(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,V(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}}const H={},X=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(H[t]=H[t]||new Y);await Promise.all(i)},z=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=H[t]=H[t]||new Y(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let Z,K=0;const q=()=>K++,J={};let Q;const $=t=>{Q=t,Z&&Z.postMessage({type:"setBLog",body:{value:!!t}})};let tt=!1;const et=t=>{tt=t,Z&&Z.postMessage({type:"setBDebug",body:{value:!!t}})},it={},rt={},nt={std:{version:"1.2.0",path:M(L+"../../dynamsoft-capture-vision-std@1.2.0/dist/")},core:{version:"3.2.10",path:L}},st=new Proxy(nt,{get(t,e,i){let r=Reflect.get(t,e,i);return r&&r.path&&(r=r.path),r}}),ot={dip:{wasm:!0}},at=async t=>{let e;t instanceof Array||(t=t?[t]:[]);{let t=H.core;e=!t||t.isEmpty}let i=new Map;for(let e of t){if(e=e.toLowerCase(),"std"==e||"core"==e)continue;if(!ot[e])throw Error("Module '"+e+"' not existed.");let t=ot[e].deps;if(null==t?void 0:t.length)for(let e of t){let t=H[e];i.has(e)||i.set(e,!t||t.isEmpty)}let r=H[e];i.has(e)||i.set(e,!r||r.isEmpty)}let r=[];e&&r.push("core"),r.push(...i.keys()),await z(r,(async()=>{const t=[...i.entries()].filter((t=>t[1])).map((t=>t[0])),r={};for(let t in st){if("rootDirectory"==t)continue;let e=st[t];st.rootDirectory&&(e.startsWith("http://")||e.startsWith("https://")||(e=st.rootDirectory+"/"+e)),r[t]=M(e)}const n={};for(let e of t)n[e]=ot[e];const s={engineResourcePaths:r,autoResources:n,names:t};let o=new Y;if(e){s.needLoadCore=!0;let t=r.core+ht._workerName;r.rootDirectory&&(t=r.rootDirectory+t),t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),Z=new Worker(t),Z.onerror=t=>{let e=new Error(t.message);o.reject(e)},Z.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":Q&&Q(e.message);break;case"task":try{J[r](n),delete J[r]}catch(t){throw delete J[r],t}break;case"event":try{J[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!Q,s.bd=tt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await X("worker");let a=K++;J[a]=t=>{if(t.success)Object.assign(it,t.versions),"{}"!==JSON.stringify(t.versions)&&(ht._versions=t.versions),o.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),o.reject(e)}},Z.postMessage({type:"loadWasm",body:s,id:a}),e&&z("worker",(()=>Promise.resolve())),await o}))};class ht{static get engineResourcePaths(){return st}static set engineResourcePaths(t){Object.assign(nt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return Q}static set _onLog(t){$(t)}static get _bDebug(){return tt}static set _bDebug(t){et(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!H[t]&&H[t].isFulfilled}static async loadWasm(t){return await at(t)}static async detectEnvironment(){return await(async()=>({wasm:U,worker:j,getUserMedia:G,camera:await W(),browser:N.browser,version:N.version,OS:N.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.2.10(Worker: ${it.core&&it.core.worker||"Not Loaded"}, Wasm: ${it.core&&it.core.wasm||"Not Loaded"})`}static enableLogging(){O._onLog=console.log,ht._onLog=console.log}static disableLogging(){O._onLog=null,ht._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var lt,ct,ut,dt,ft,gt,mt,pt,_t,vt,yt;ht._bSupportDce4Module=-1,ht._bSupportIRTModule=-1,ht._versions=null,ht._workerName="core.worker.js",ht.browserInfo=N,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(lt||(lt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(ct||(ct={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID"}(ut||(ut={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(dt||(dt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(ft||(ft={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(gt||(gt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(mt||(mt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(pt||(pt={})),function(t){t[t.IRUT_NULL=0]="IRUT_NULL",t[t.IRUT_COLOUR_IMAGE=1]="IRUT_COLOUR_IMAGE",t[t.IRUT_SCALED_DOWN_COLOUR_IMAGE=2]="IRUT_SCALED_DOWN_COLOUR_IMAGE",t[t.IRUT_GRAYSCALE_IMAGE=4]="IRUT_GRAYSCALE_IMAGE",t[t.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE=8]="IRUT_TRANSOFORMED_GRAYSCALE_IMAGE",t[t.IRUT_ENHANCED_GRAYSCALE_IMAGE=16]="IRUT_ENHANCED_GRAYSCALE_IMAGE",t[t.IRUT_PREDETECTED_REGIONS=32]="IRUT_PREDETECTED_REGIONS",t[t.IRUT_BINARY_IMAGE=64]="IRUT_BINARY_IMAGE",t[t.IRUT_TEXTURE_DETECTION_RESULT=128]="IRUT_TEXTURE_DETECTION_RESULT",t[t.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE=256]="IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE",t[t.IRUT_TEXTURE_REMOVED_BINARY_IMAGE=512]="IRUT_TEXTURE_REMOVED_BINARY_IMAGE",t[t.IRUT_CONTOURS=1024]="IRUT_CONTOURS",t[t.IRUT_LINE_SEGMENTS=2048]="IRUT_LINE_SEGMENTS",t[t.IRUT_TEXT_ZONES=4096]="IRUT_TEXT_ZONES",t[t.IRUT_TEXT_REMOVED_BINARY_IMAGE=8192]="IRUT_TEXT_REMOVED_BINARY_IMAGE",t[t.IRUT_CANDIDATE_BARCODE_ZONES=16384]="IRUT_CANDIDATE_BARCODE_ZONES",t[t.IRUT_LOCALIZED_BARCODES=32768]="IRUT_LOCALIZED_BARCODES",t[t.IRUT_SCALED_UP_BARCODE_IMAGE=65536]="IRUT_SCALED_UP_BARCODE_IMAGE",t[t.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE=131072]="IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE",t[t.IRUT_COMPLEMENTED_BARCODE_IMAGE=262144]="IRUT_COMPLEMENTED_BARCODE_IMAGE",t[t.IRUT_DECODED_BARCODES=524288]="IRUT_DECODED_BARCODES",t[t.IRUT_LONG_LINES=1048576]="IRUT_LONG_LINES",t[t.IRUT_CORNERS=2097152]="IRUT_CORNERS",t[t.IRUT_CANDIDATE_QUAD_EDGES=4194304]="IRUT_CANDIDATE_QUAD_EDGES",t[t.IRUT_DETECTED_QUADS=8388608]="IRUT_DETECTED_QUADS",t[t.IRUT_LOCALIZED_TEXT_LINES=16777216]="IRUT_LOCALIZED_TEXT_LINES",t[t.IRUT_RECOGNIZED_TEXT_LINES=33554432]="IRUT_RECOGNIZED_TEXT_LINES",t[t.IRUT_NORMALIZED_IMAGES=67108864]="IRUT_NORMALIZED_IMAGES",t[t.IRUT_SHORT_LINES=134217728]="IRUT_SHORT_LINES",t[t.IRUT_ALL=268435455]="IRUT_ALL"}(_t||(_t={})),function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(vt||(vt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(yt||(yt={}));var wt=Object.freeze({__proto__:null,CoreModule:ht,get EnumBufferOverflowProtectionMode(){return r},get EnumCapturedResultItemType(){return lt},get EnumColourChannelUsageType(){return n},get EnumCornerType(){return ct},get EnumErrorCode(){return ut},get EnumGrayscaleEnhancementMode(){return dt},get EnumGrayscaleTransformationMode(){return ft},get EnumImagePixelFormat(){return s},get EnumImageTagType(){return gt},get EnumIntermediateResultUnitType(){return _t},get EnumPDFReadingMode(){return mt},get EnumRasterDataSource(){return pt},get EnumRegionObjectElementType(){return vt},get EnumSectionType(){return yt},ImageSourceAdapter:O,_isArc:t=>!(!c(t)||!l(t.x)||!l(t.y)||!l(t.radius)||t.radius<0||!l(t.startAngle)||!l(t.endAngle)),_isContour:t=>!!c(t)&&!!a(t.points)&&0!=t.points.length&&!t.points.some((t=>!m(t))),_isDSImageData:u,_isDSRect:d,_isImageTag:f,_isLineSegment:g,_isPoint:m,_isPolygon:p,_isQuad:_,_isRect:v,get bDebug(){return tt},bSupportBigInt:E,checkIsLink:function(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)},compareVersion:w,doOrWaitAsyncDependency:z,engineResourcePaths:nt,getNextTaskID:q,innerVersions:it,loadWasm:at,mapAsyncDependency:H,mapPackageRegister:rt,mapTaskCallBack:J,newAsyncDependency:t=>{let e=H[t],i=!1;return e?e.isEmpty?e.task=()=>{}:i=!0:e=H[t]=new Y((()=>{})),{p:e,justWait:i}},get onLog(){return Q},requestResource:y,setBDebug:et,setOnLog:$,waitAsyncDependency:X,get worker(){return Z},workerAutoResources:ot}); -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft License JS Edition - * @website https://www.dynamsoft.com - * @copyright Copyright 2024, Dynamsoft Corporation - * @author Dynamsoft - * @version 3.2.10 - * @fileoverview Dynamsoft JavaScript Library for Core - * More info DL JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-module.html - */const Et="undefined"==typeof self,Ct=Et?{}:self,Tt=(()=>{if(!Et&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),bt=t=>{if(null==t&&(t="./"),Et);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},St=t=>t&&"object"==typeof t&&"function"==typeof t.then;class It extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(St(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,St(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}}const xt=" is not allowed to change after `createInstance` or `loadWasm` is called.",At=!Et&&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"))||"",Rt=(t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`license`"+xt);i._license=e};!Et&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ot=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{const i=t;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+xt);i._licenseServer=Ot(e)},Lt=(t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+xt);i._deviceFriendlyName=e||""};let Mt,Ft,Pt,kt,Bt;"undefined"!=typeof navigator&&(Mt=navigator,Ft=Mt.userAgent,Pt=Mt.platform,kt=Mt.mediaDevices),function(){if(!Et){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Mt.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Pt,search:"Win"},Mac:{str:Pt},Linux:{str:Pt}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Ft,o=n.search||e,a=n.verStr||Ft,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Ft,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Ft.indexOf("Windows NT")&&(n="HarmonyOS"),Bt={browser:i,version:r,OS:n}}Et&&(Bt={browser:"ssr",version:0,OS:"ssr"})}(),"undefined"!=typeof WebAssembly&&Ft&&(!/Safari/.test(Ft)||/Chrome/.test(Ft)||/\(.+\s11_2_([2-6]).*\)/.test(Ft)),kt&&kt.getUserMedia,"Chrome"===Bt.browser&&Bt.version>66||"Safari"===Bt.browser&&Bt.version>13||"OPR"===Bt.browser&&Bt.version>43||"Edge"===Bt.browser&&Bt.version;const Nt=async()=>(at("license"),z("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Ot(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Ct.crypto||(s="Please upgrade your browser to support online key."),Ct.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+xt)})(jt),o=new It;jt._pLoad.task=o,(async()=>{try{await jt._pLoad}catch(t){}})();let a=q();J[a]=e=>{if(e.message&&jt._onAuthMessage){let t=jt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(Q&&Q("init license success"),e.message&&console.warn(e.message),ht._bSupportIRTModule=e.bSupportIRTModule,ht._bSupportDce4Module=e.bSupportDce4Module,jt.bPassValidation=!0):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){let t=nt.license;nt.rootDirectory&&(t=nt.rootDirectory+"/"+t),t=bt(t),(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.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 t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:jt._bNeverShowDialog,engineResourcePath:t,_onLog:Q},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await X("worker"),Z.postMessage({type:"dynamsoft",body:{v:"3.2.10",brtk:!!t,bptk:1===t,l:e,os:Bt,fn:jt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),jt.bCallInitLicense=!0,await o})));let Ut;rt.license={},rt.license.dynamsoft=Nt,rt.license.getAR=async()=>{{let t=H.dynamsoft_inited;t&&t.isRejected&&await t}return Z?new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success){delete i.success;{let t=jt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},Z.postMessage({type:"getAR",id:i})})):null};class jt{static setLicenseServer(t){Dt(jt,t)}static get license(){return this._license}static set license(t){Rt(jt,t)}static get licenseServer(){return this._licenseServer}static set licenseServer(t){Dt(jt,t)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(t){Lt(jt,t)}static initLicense(t,e){if(Rt(jt,t),jt.bCallInitLicense=!0,e)return Nt()}static setDeviceFriendlyName(t){Lt(jt,t)}static getDeviceFriendlyName(){return jt._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await z("dynamsoft_uuid",(async()=>{await at();let t=new It,e=q();J[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Z.postMessage({type:"getDeviceUUID",id:e}),Ut=await t})),Ut))()}}jt._pLoad=new It,jt.bPassValidation=!1,jt.bCallInitLicense=!1,jt._license=At,jt._licenseServer=[],jt._deviceFriendlyName="",null==nt.license&&(nt.license=Tt),ot.license={wasm:!0},rt.license.LicenseManager=jt;const Gt="1.2.0";"string"!=typeof nt.std&&w(nt.std.version,Gt)<0&&(nt.std={version:Gt,path:bt(Tt+`../../dynamsoft-capture-vision-std@${Gt}/dist/`)});var Wt=Object.freeze({__proto__:null,LicenseManager:jt,LicenseModule:class{static getVersion(){return`3.2.10(Worker: ${it.license&&it.license.worker||"Not Loaded"}, Wasm: ${it.license&&it.license.wasm||"Not Loaded"})`}}}); -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Capture Vision Router JS Edition - * @website http://www.dynamsoft.com - * @copyright Copyright 2024, Dynamsoft Corporation - * @author Dynamsoft - * @version "2.2.10" - * @fileoverview Dynamsoft JavaScript Library for Capture Vision - * More info on cvr JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html - */const Vt=t=>t&&"object"==typeof t&&"function"==typeof t.then;class Yt extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Vt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Vt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}}class Ht{constructor(){this.addResultReceiver=null,this.removeResultReceiver=null,this.getOriginalImage=null}}var Xt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const zt="undefined"==typeof self,Zt=(()=>{if(!zt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Kt=t=>{if(null==t&&(t="./"),zt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var qt;null==nt.cvr&&(nt.cvr=Zt),ot.cvr={js:!0,wasm:!0,deps:["license","dip"]},rt.cvr={};const Jt="1.2.0";"string"!=typeof nt.std&&w(nt.std.version,Jt)<0&&(nt.std={version:Jt,path:Kt(Zt+`../../dynamsoft-capture-vision-std@${Jt}/dist/`)});const Qt="2.2.10";(!nt.dip||"string"!=typeof nt.dip&&w(nt.dip.version,Qt)<0)&&(nt.dip={version:Qt,path:Kt(Zt+`../../dynamsoft-image-processing@${Qt}/dist/`)});class $t{static getVersion(){return this._version}}var te,ee;function ie(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;ie(t.referencedItem,e)}}$t._version=`2.2.10(Worker: ${null===(qt=it.cvr)||void 0===qt?void 0:qt.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(te||(te={})),function(t){t[t.IRUT_NULL=0]="IRUT_NULL",t[t.IRUT_COLOUR_IMAGE=1]="IRUT_COLOUR_IMAGE",t[t.IRUT_SCALED_DOWN_COLOUR_IMAGE=2]="IRUT_SCALED_DOWN_COLOUR_IMAGE",t[t.IRUT_GRAYSCALE_IMAGE=4]="IRUT_GRAYSCALE_IMAGE",t[t.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE=8]="IRUT_TRANSOFORMED_GRAYSCALE_IMAGE",t[t.IRUT_ENHANCED_GRAYSCALE_IMAGE=16]="IRUT_ENHANCED_GRAYSCALE_IMAGE",t[t.IRUT_PREDETECTED_REGIONS=32]="IRUT_PREDETECTED_REGIONS",t[t.IRUT_BINARY_IMAGE=64]="IRUT_BINARY_IMAGE",t[t.IRUT_TEXTURE_DETECTION_RESULT=128]="IRUT_TEXTURE_DETECTION_RESULT",t[t.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE=256]="IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE",t[t.IRUT_TEXTURE_REMOVED_BINARY_IMAGE=512]="IRUT_TEXTURE_REMOVED_BINARY_IMAGE",t[t.IRUT_CONTOURS=1024]="IRUT_CONTOURS",t[t.IRUT_LINE_SEGMENTS=2048]="IRUT_LINE_SEGMENTS",t[t.IRUT_TEXT_ZONES=4096]="IRUT_TEXT_ZONES",t[t.IRUT_TEXT_REMOVED_BINARY_IMAGE=8192]="IRUT_TEXT_REMOVED_BINARY_IMAGE",t[t.IRUT_CANDIDATE_BARCODE_ZONES=16384]="IRUT_CANDIDATE_BARCODE_ZONES",t[t.IRUT_LOCALIZED_BARCODES=32768]="IRUT_LOCALIZED_BARCODES",t[t.IRUT_SCALED_UP_BARCODE_IMAGE=65536]="IRUT_SCALED_UP_BARCODE_IMAGE",t[t.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE=131072]="IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE",t[t.IRUT_COMPLEMENTED_BARCODE_IMAGE=262144]="IRUT_COMPLEMENTED_BARCODE_IMAGE",t[t.IRUT_DECODED_BARCODES=524288]="IRUT_DECODED_BARCODES",t[t.IRUT_LONG_LINES=1048576]="IRUT_LONG_LINES",t[t.IRUT_CORNERS=2097152]="IRUT_CORNERS",t[t.IRUT_CANDIDATE_QUAD_EDGES=4194304]="IRUT_CANDIDATE_QUAD_EDGES",t[t.IRUT_DETECTED_QUADS=8388608]="IRUT_DETECTED_QUADS",t[t.IRUT_LOCALIZED_TEXT_LINES=16777216]="IRUT_LOCALIZED_TEXT_LINES",t[t.IRUT_RECOGNIZED_TEXT_LINES=33554432]="IRUT_RECOGNIZED_TEXT_LINES",t[t.IRUT_NORMALIZED_IMAGES=67108864]="IRUT_NORMALIZED_IMAGES",t[t.IRUT_SHORT_LINES=134217728]="IRUT_SHORT_LINES",t[t.IRUT_ALL=134217727]="IRUT_ALL"}(ee||(ee={}));class re{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(ht.browserInfo.OS)?2048:4096,this._isa=null,this._dsImage=null,this._instanceID=void 0,this._bPauseScan=!0,this._bNeedOutputOriginalImage=!1,this._canvas=null,this._irrRegistryState=Xt,this._resultReceiverSet=new Set,this._isaStateListenerSet=new Set,this._resultFilterSet=new Set,this._intermediateResultReceiverSet=new Set,this._intermediateResultManager=null,this._templateName="Default",this._bOpenDetectVerify=!1,this._bOpenNormalizeVerify=!1,this._bOpenBarcodeVerify=!1,this._bOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._compressRate=0,this._dynamsoft=!1,this.captureInParallel=!0,this.bDestroyed=!1,this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this),this._promiseStartScan=null}get disposed(){return this.bDestroyed}static async createInstance(){if(!rt.license)throw Error("Module `license` is not existed.");await rt.license.dynamsoft(),await at(["cvr"]);const t=new re,e=new Yt;let i=q();return J[i]=async i=>{var r;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(i.outputSettings),$t._version=`2.2.10(Worker: ${null===(r=it.cvr)||void 0===r?void 0:r.worker}, Wasm: ${i.version})`,0===ht.bSupportDce4Module&&(t._intermediateResultManager=t.getIntermediateResultManager(!0)),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},Z.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){this._isa.getCameraView().setScanLaserVisible(!0);for(let e of this._resultReceiverSet)this._bNeedOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag},i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of this._resultReceiverSet)t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of this._resultReceiverSet)if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._bNeedOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(this._checkIsDisposed(),t){if(this._isa=t,t.isCameraEnhancer){this._intermediateResultManager&&(this._isa._intermediateResultReceiver.isDce=!0,this._intermediateResultManager.addResultReceiver(this._isa._intermediateResultReceiver));const t=this._isa.getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,this._resultReceiverSet.add(e)}}}else this._isa=null}getInput(){return this._isa}addImageSourceStateListener(t){if(this._checkIsDisposed(),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&this._isaStateListenerSet.add(t)}removeImageSourceStateListener(t){return this._checkIsDisposed(),this._isaStateListenerSet.delete(t)}addResultReceiver(t){if(this._checkIsDisposed(),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(this._resultReceiverSet.add(t),this._setCrrRegistry())}removeResultReceiver(t){this._checkIsDisposed(),this._resultReceiverSet.delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of this._resultReceiverSet)e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Yt;let i=q();return J[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},Z.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(this._checkIsDisposed(),"object"!=typeof t)return console.warn("Invalid filter.");if(t&&Object.keys(t)){this._resultFilterSet.add(t),this._handleFilterSwitch();for(let t of this._resultFilterSet)await this._enableResultCrossVerification(t.verificationEnabled),await this._enableResultDeduplication(t.duplicateFilterEnabled),await this._setDuplicateForgetTime(t.duplicateForgetTime)}}async removeResultFilter(t){this._checkIsDisposed(),this._resultFilterSet.delete(t),this._handleFilterSwitch();for(let t of this._resultFilterSet)await this._enableResultCrossVerification(t.verificationEnabled),await this._enableResultDeduplication(t.duplicateFilterEnabled),await this._setDuplicateForgetTime(t.duplicateForgetTime)}_handleFilterSwitch(){this._bOpenBarcodeVerify=!1,this._bOpenLabelVerify=!1,this._bOpenDetectVerify=!1,this._bOpenNormalizeVerify=!1;for(let t of this._resultFilterSet)t.isResultCrossVerificationEnabled(lt.CRIT_BARCODE)&&(this._bOpenBarcodeVerify=!0),t.isResultCrossVerificationEnabled(lt.CRIT_TEXT_LINE)&&(this._bOpenLabelVerify=!0),t.isResultCrossVerificationEnabled(lt.CRIT_DETECTED_QUAD)&&(this._bOpenDetectVerify=!0),t.isResultCrossVerificationEnabled(lt.CRIT_NORMALIZED_IMAGE)&&(this._bOpenNormalizeVerify=!0)}async startCapturing(t="Default"){if(this._checkIsDisposed(),!this._bPauseScan)return;if(!this._isa)throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");const e=await this.containsTask(t);return await at(e),this._isa.isCameraEnhancer&&(e.includes("ddn")?this._isa.setPixelFormat(s.IPF_ABGR_8888):this._isa.setPixelFormat(s.IPF_GRAYSCALED)),void 0!==this._isa.singleFrameMode&&"disabled"!==this._isa.singleFrameMode?(this._templateName=t,void this._isa.on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(this._isa.getColourChannelUsageType()===n.CCUT_AUTO&&this._isa.setColourChannelUsageType(e.includes("ddn")?n.CCUT_FULL_CHANNEL:n.CCUT_Y_CHANNEL_ONLY),this._promiseStartScan&&this._promiseStartScan.isPending?this._promiseStartScan:(this._promiseStartScan=new Yt(((e,i)=>{if(this.disposed)return;let r=q();J[r]=async r=>{if(this._promiseStartScan&&!this._promiseStartScan.isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}for(let t of this._resultFilterSet)await this.addResultFilter(t);this._bPauseScan=!1,this._bNeedOutputOriginalImage=r.bNeedOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&this._isa.startFetching(),this._loopReadVideo(t),e()}),0),this._isa.isCameraEnhancer&&this._isa.getCameraView().setScanLaserVisible(!0)}},Z.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),await this._promiseStartScan))}stopCapturing(){this._checkIsDisposed(),this._isa&&(this._isa.isCameraEnhancer&&(this._isa.getCameraView().setScanLaserVisible(!1),void 0!==this._isa.singleFrameMode&&"disabled"!==this._isa.singleFrameMode)?this._isa.off("singleFrameAcquired",this._singleFrameModeCallbackBind):(this._isa.stopFetching(),this._clearVerifyList(),this._averageProcessintTimeArray=[],this._averageTime=999,this._bPauseScan=!0,this._promiseStartScan=null,this._isa.setColourChannelUsageType(n.CCUT_AUTO)))}async _clearVerifyList(){let t=q();const e=new Yt;return J[t]=async t=>{if(t.success)return e.resolve();{let i=new Error(t.message);return i.stack=t.stack+"\n"+i.stack,e.reject(i)}},Z.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e}async _getIntermediateResult(){this._checkIsDisposed();let t=q();const e=new Yt;return J[t]=async t=>{if(t.success)e.resolve(t.result);else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject(i)}},Z.postMessage({type:"cvr_getIntermediateResult",id:t,instanceID:this._instanceID}),e}async containsTask(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this._dynamsoft=!0,this.disposed||this._bPauseScan)return;if(this._isa.isBufferEmpty())if(this._isa.hasNextImageToFetch())for(let t of this._isaStateListenerSet)t.onImageSourceStateReceived&&t.onImageSourceStateReceived(te.ISS_BUFFER_EMPTY);else if(!this._isa.hasNextImageToFetch())for(let t of this._isaStateListenerSet)t.onImageSourceStateReceived&&t.onImageSourceStateReceived(te.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||this._isa.isBufferEmpty())try{this._isa.isBufferEmpty()&&re._onLog&&re._onLog("buffer is empty so fetch image"),re._onLog&&re._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=this._isa.fetchImage(),re._onLog&&re._onLog(`DCE: finish fetching a frame: ${Date.now()}`),this._isa.setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(this._isa.setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=this._isa.getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of this._resultReceiverSet)this._bNeedOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(re._onLog&&re._onLog("no js handle time: "+(Date.now()-e)),this._bPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let t of this._resultReceiverSet)if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._bOpenDetectVerify,isNormalizeVerifyOpen:this._bOpenNormalizeVerify,isBarcodeVerifyOpen:this._bOpenBarcodeVerify,isLabelVerifyOpen:this._bOpenLabelVerify}),re._onLog){const t=Date.now()-e;t>10&&re._onLog(`draw result time: ${t}`)}}const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of this._resultReceiverSet)t.onDecodedBarcodesReceived&&i.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&i.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&i.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&i.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&i.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(i.items=i.items.filter((t=>!t.isFilter)),i.barcodeResultItems&&(i.barcodeResultItems=i.barcodeResultItems.filter((t=>!t.isFilter))),i.textLineResultItems&&(i.textLineResultItems=i.textLineResultItems.filter((t=>!t.isFilter))),i.detectedQuadResultItems&&(i.detectedQuadResultItems=i.detectedQuadResultItems.filter((t=>!t.isFilter))),i.normalizedImageResultItems&&(i.normalizedImageResultItems=i.normalizedImageResultItems.filter((t=>!t.isFilter))),i.parsedResultItems&&(i.parsedResultItems=i.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(i));const n=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,re._onLog&&(re._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),re._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),re._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),re._onLog(`averageTime: ${this._averageTime}`))),re._onLog){const t=Date.now()-n;t>10&&re._onLog(`fetch image calculate time: ${t}`)}re._onLog&&re._onLog(`time finish decode: ${Date.now()}`),re._onLog&&re._onLog("main time: "+(Date.now()-e)),re._onLog&&re._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{this._isa.stopFetching(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._isa.startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3)),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e="Default"){this._checkIsDisposed();const i=await this.containsTask(e);let r;if(await at(i),this._dynamsoft=!1,u(t))r=await this._captureDsimage(t,e);else if("string"==typeof t)r="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)r=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)r=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)r=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");r=await this._captureVideo(t,e)}return r}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await y(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(this._compressRate=this.maxCvsSideLength/o,i=Math.round(n*this._compressRate),r=Math.round(s*this._compressRate)):(i=n,r=s),this._canvas||(this._canvas=document.createElement("canvas"));const a=this._canvas;return a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(this._compressRate=this.maxCvsSideLength/o,i=Math.round(n*this._compressRate),r=Math.round(s*this._compressRate)):(i=n,r=s),this._canvas||(this._canvas=document.createElement("canvas"));const a=this._canvas;return a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(t,e){const{bytes:i,width:r,height:n,stride:s,format:o}=t;let a=q();const h=new Yt;return J[a]=async e=>{var i,r;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h.reject(t)}{const n=Date.now();re._onLog&&(re._onLog(`get result time from worker: ${n}`),re._onLog("worker to main time consume: "+(n-e.workerReturnMsgTime)));try{const n=e.captureResult;t.bytes=e.bytes;for(let e of n.items)0!==this._compressRate&&ie(e,this._compressRate),e.type===lt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===lt.CRIT_NORMALIZED_IMAGE?null===(i=rt.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===lt.CRIT_PARSED_RESULT&&(null===(r=rt.dcp)||void 0===r||r.handleParsedResultItem(e));if(this._dynamsoft)for(let t of this._resultFilterSet)t.onDecodedBarcodesReceived(n.items),t.onRecognizedTextLinesReceived(n.items),t.onDetectedQuadsReceived(n.items),t.onNormalizedImagesReceived(n.items);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===lt.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===lt.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===lt.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===lt.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===lt.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(n);s.barcodeResultItems.length&&(n.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(n.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(n.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(n.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(n.parsedResultItems=s.parsedResultItems);const o=n.intermediateResult;if(o){let e=0;for(let i of this._intermediateResultReceiverSet){e++;for(let r of o){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;i[r.info.callbackName]&&i[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else i[r.info.callbackName]&&i[r.info.callbackName](r.result,r.info);e===this._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}return n&&n.intermediateResult&&delete n.intermediateResult,this._compressRate=0,h.resolve(n)}catch(t){return h.reject(t)}}},re._onLog&&re._onLog(`send buffer to worker: ${Date.now()}`),Z.postMessage({type:"cvr_capture",id:a,instanceID:this._instanceID,body:{bytes:i,width:r,height:n,stride:s,format:o,templateName:e||"",dynamsoft:this._dynamsoft}},[i.buffer]),h}async initSettings(t){return this._checkIsDisposed(),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.startsWith("{")?this._currentSettings=JSON.parse(t):t=await y(t,"text"):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=q();J[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=q();J[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"Default"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t="Default"){this._checkIsDisposed();const e=await this.containsTask(t);return await at(e),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>E&&"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){this._checkIsDisposed();const i=await this.containsTask(t);return await at(i),await new Promise(((i,r)=>{let n=q();J[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._bNeedOutputOriginalImage=t.bNeedOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},Z.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return this._checkIsDisposed(),await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getIntermediateResultManager(t){if(this._checkIsDisposed(),!t&&0!==ht.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return this._intermediateResultManager||(this._intermediateResultManager=new Ht,this._intermediateResultManager.addResultReceiver=async t=>{if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),this._handleIntermediateResultReceiver();let e=-1,i={};if(!t.isDce){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await(async()=>await new Promise(((t,r)=>{let n=q();J[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},Z.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:String(e),observedTaskMap:i}})})))()},this._intermediateResultManager.removeResultReceiver=async t=>(this._intermediateResultReceiverSet.delete(t),this._handleIntermediateResultReceiver(),await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._instanceID,body:{receiverObj:this._irrRegistryState}})}))),this._intermediateResultManager.getOriginalImage=()=>this._dsImage),this._intermediateResultManager}_handleIntermediateResultReceiver(){for(let t in this._irrRegistryState)this._irrRegistryState[t]=!1;for(let t of this._intermediateResultReceiverSet)if(t.isDce)this._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let e in t)this._irrRegistryState[e]||(this._irrRegistryState[e]=!!t[e])}contains(t,e){return function(t,e){let i=e.x,r=e.y,n=t[0].x,s=t[0].y,o=t[1].x,a=t[1].y,h=t[2].x,l=t[2].y,c=t[3].x,u=t[3].y,d=p(i,r,n,s,o,a),f=p(i,r,o,a,h,l),g=p(i,r,h,l,c,u),m=p(i,r,c,u,n,s);function p(t,e,i,r,n,s){return(t-i)*(s-r)-(e-r)*(n-i)}return d>=0&&f>=0&&g>=0&&m>=0||d<=0&&f<=0&&g<=0&&m<=0}(t,e)}async parseRequiredResources(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){this._checkIsDisposed(),this._promiseStartScan&&this.stopCapturing(),this._isa=null,this._resultReceiverSet.clear(),this._isaStateListenerSet.clear(),this._resultFilterSet.clear(),this.bDestroyed=!0;let t=q();J[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Z.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}async _enableResultCrossVerification(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:this._instanceID,body:{verificationEnabled:t}})}))}async _enableResultDeduplication(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})}))}async _setDuplicateForgetTime(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:this._instanceID,body:{duplicateForgetTime:t}})}))}async _getDuplicateForgetTime(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.time);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_getDuplicateForgetTime",id:r,instanceID:this._instanceID,body:{type:t}})}))}async _setThresholdValue(t,e,i){return await at("ddn"),await new Promise(((r,n)=>{let s=q();J[s]=async t=>{if(t.success)return r();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Z.postMessage({type:"ddn_setThresholdValue",id:s,instanceID:this._instanceID,body:{threshold:t,leftLimit:e,rightLimit:i}})}))}_checkIsDisposed(){if(this.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}}var ne=Object.freeze({__proto__:null,CaptureVisionRouter:re,CaptureVisionRouterModule:$t,CapturedResultReceiver:class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},get EnumImageSourceState(){return te},IntermediateResultManager:Ht,IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=_t.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}}); -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Camera Enhancer JS Edition - * @website https://www.dynamsoft.com - * @copyright Copyright 2024, Dynamsoft Corporation - * @author Dynamsoft - * @version 4.0.2 - * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer - * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */const se="undefined"==typeof self,oe=(()=>{if(!se&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();null==nt.dce&&(nt.dce=oe),ot.dce={wasm:!1,js:!1},rt.dce={};function ae(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function he(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}let le,ce,ue,de,fe;"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(le=navigator,ce=le.userAgent,ue=le.platform,de=le.mediaDevices),function(){if(!se){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:le.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:ue,search:"Win"},Mac:{str:ue},Linux:{str:ue}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||ce,o=n.search||e,a=n.verStr||ce,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||ce,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=ce.indexOf("Windows NT")&&(n="HarmonyOS"),fe={browser:i,version:r,OS:n}}se&&(fe={browser:"ssr",version:0,OS:"ssr"})}();const ge="undefined"!=typeof WebAssembly&&ce&&!(/Safari/.test(ce)&&!/Chrome/.test(ce)&&/\(.+\s11_2_([2-6]).*\)/.test(ce)),me=!("undefined"==typeof Worker),pe=!(!de||!de.getUserMedia),_e=async()=>{let t=!1;if(pe)try{(await de.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===fe.browser&&fe.version>66||"Safari"===fe.browser&&fe.version>13||"OPR"===fe.browser&&fe.version>43||"Edge"===fe.browser&&fe.version;var ve={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,E,C,T,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=S.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=S,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,r=e.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 x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new b.Point(t.x-e.x,t.y-e.y),n=b.util.rotateVector(r,i);return new b.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),r=b.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=b.util.createVector(t,e),n=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(r,n),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(r,s),n)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,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(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var T=Math.sqrt(1-E/(_*v));i*=T,s*=T}else C=(o===a?-1:1)*Math.sqrt(E/(_*y+v*w));var S=C*i*p/s,I=-C*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,R=n(1,0,(m-S)/i,(p-I)/s),O=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&O>0?O-=2*l:1===a&&O<0&&(O+=2*l);for(var D=Math.ceil(Math.abs(O/l*2)),L=[],M=O/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kC)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],T=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var I,x,A,R=C.length,O=R;R--;)I=(A=1-(f=C[R]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,T[0][R]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,T[1][R]=x;T[0][O]=e,T[1][O]=i,T[0][O+1]=a,T[1][O+1]=h;var D=[{x:y.apply(null,T[0]),y:y.apply(null,T[1])},{x:w.apply(null,T[0]),y:w.apply(null,T[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=b.document.documentElement,n=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=n,!o){if(!f(w,E,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,E,n),void a(t));h()}}(l)})),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,r,n){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},b.util.animate(b.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",T=0,b=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),E.minX=i,E.minY=r,E.viewBoxWidth=n,E.viewBoxHeight=o,y?(E.width=n,E.height=o):(E.width=s(d),E.height=s(f),c=E.width/n,u=E.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),T=E.width-n*c,b=E.height-o*c,"Mid"===p.alignX&&(T/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(T=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+T)+" "+(r*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),E}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function E(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(t){return t.flipX!==t.flipY}function T(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function b(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=E(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),C(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),T(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=E(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),C(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),T(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),C=_(f,y,w),T=e.gestureScale;if(C)return!1;if(T)o=e.scaleX*T,a=e.scaleY*T;else{if(s=E(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=b/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(b))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=E(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=E,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new b.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.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,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.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))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.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(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.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 t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,r=b.util.toFixed,n=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?b.util.loadImage(e,(function(e,n){if(e){var s=new b.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?b.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=b.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new b.Point(r.x,r.y),n=new b.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=b.util.invertTransform(i),n=this.restorePointerVpt(e);return b.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),r=b.util.transformPoint(i,this.viewportTransform),n=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof b.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==r&&(b.Canvas[r]=b.StaticCanvas[r])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(b.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e:e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new b.Point(v(r,s),v(n,o)),h=new b.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return b.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):b.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+b.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=l>y||c>w;v=E||(l<.9*y||c<.9*w)&&y>h&&w>h,E&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof r?r=E[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),n=new b.Point(t.x,t.y),this.angle&&(n=b.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=b.util.cos(r)*n,o=b.util.sin(r)*n;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===b.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=b.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=b.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return b.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=b.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],b.util.enlivenObjectEnlivables(i,i,(function(){var r=new b.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,(function(t,r){e&&e(new b.Image(t,i),r)}),null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,r){var n=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(n["xlink:href"],i,e(r?b.util.object.clone(r):{},n))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){b.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=n,n},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,T||(n+=m[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=T?m[s+3]:n}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=r(1e3*s(b-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(n(i(L*p,2)+i(M*_,2))/1e3)),(S=w[L][M])>0&&(x+=S,A+=S*c[I=4*(F*e+b)],R+=S*c[I+1],O+=S*c[I+2],D+=S*c[I+3]))}d[I=4*(T*a+h)]=A/x,d[I+1]=R/x,d[I+2]=O/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(L=4*(D+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],T+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=T/w,m[v+2]=b/w,m[v+3]=S/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+C*r+o,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,E=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,E=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+E,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);b.Object._fromObject("IText",e,i,"text")}}(),T=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=b.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=T(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:T(r[i-1])}:n?this.styles[t+i]={0:T(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?T(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=T(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=T(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},ye={};function we(t){var e=ye[t];if(void 0!==e)return e.exports;var i=ye[t]={exports:{}};return ve[t](i,i.exports,we),i.exports}we.d=(t,e)=>{for(var i in e)we.o(e,i)&&!we.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},we.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ee={};(()=>{let t;we.d(Ee,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?we(653).fabric:{version:"5.2.1"}})();var Ce,Te,be,Se,Ie=Ee.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Ce||(Ce={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(Te||(Te={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(be||(be={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Se||(Se={}));const xe=t=>"number"==typeof t&&!Number.isNaN(t),Ae=t=>"string"==typeof t;var Re,Oe,De,Le,Me,Fe;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(Me||(Me={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(Fe||(Fe={}));class Pe{get mediaType(){return new Map([["rect",Ce.DIMT_RECTANGLE],["quad",Ce.DIMT_QUADRILATERAL],["text",Ce.DIMT_TEXT],["arc",Ce.DIMT_ARC],["image",Ce.DIMT_IMAGE],["polygon",Ce.DIMT_POLYGON],["line",Ce.DIMT_LINE],["group",Ce.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(ae(this,Oe,"f")){case Te.DIS_DEFAULT:return"default";case Te.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===ae(this,De,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===ae(this,De,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),he(this,De,t,"f")}get coordinateBase(){return ae(this,De,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(Re.add(this),Oe.set(this,void 0),De.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!xe(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(Te.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(Te.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(Te.DIS_SELECTED):this.setState(Te.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){he(this,Oe,t,"f")}getState(){return ae(this,Oe,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),Be=t=>!!Ae(t)&&""!==t,Ne=u,Ue=d,je=g,Ge=p,We=m,Ve=_,Ye=v,He=t=>!(!ke(t)||"id"in t&&!xe(t.id)||"lineWidth"in t&&!xe(t.lineWidth)||"fillStyle"in t&&!Be(t.fillStyle)||"strokeStyle"in t&&!Be(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Be(t.fontFamily)||"fontSize"in t&&!xe(t.fontSize));class Xe{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(Ye(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!Ue(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var ze,Ze;class Ke{constructor(){ze.set(this,new Map),Ze.set(this,!1)}get disposed(){return ae(this,Ze,"f")}on(t,e){t=t.toLowerCase();const i=ae(this,ze,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else ae(this,ze,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=ae(this,ze,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=ae(this,ze,"f").get(t);e&&(e.length=0)}async fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=ae(this,ze,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let r=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}r.push(i)}else r=e;let s=!1;if(i.async)setTimeout((()=>{this.disposed||n.apply(i.target,r)}),0);else try{s=await n.apply(i.target,r)}catch(t){}if(!0===s)break}}}dispose(){he(this,Ze,!0,"f")}}function qe(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Je(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Qe(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}ze=new WeakMap,Ze=new WeakMap;const $e=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");r.insertAdjacentHTML("beforeend",i);for(let t=0;t0?i-1:r,hi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),he(this,ei,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new Ie.Control({positionHandler:oi,actionHandler:li(r>0?r-1:i,hi),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=Ie.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){ae(this,ei,"f")&&this.setPolygon(ae(this,ei,"f"))}setPolygon(t){if(!Ge(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else he(this,ei,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return ae(this,ei,"f")?JSON.parse(JSON.stringify(ae(this,ei,"f"))):null}}ei=new WeakMap;ii=new WeakMap,ri=new WeakMap;const ui=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else he(this,gi,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return ae(this,gi,"f")?JSON.parse(JSON.stringify(ae(this,gi,"f"))):null}}gi=new WeakMap;class qi extends Pe{constructor(t){super(new Ie.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(Te.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(Te.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class Ji{static createDrawingStyle(t){if(!He(t))throw new Error("Invalid style definition.");let e,i=Ji.USER_START_STYLE_ID;for(;ae(Ji,mi,"f",pi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in ae(Ji,mi,"f",_i))r.hasOwnProperty(t)||(r[t]=ae(Ji,mi,"f",_i)[t]);return ae(Ji,mi,"f",pi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=ae(Ji,mi,"f",pi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(ae(Ji,mi,"f",pi).values())))}static _updateDrawingStyle(t,e){if(!He(e))throw new Error("Invalid style definition.");const i=ae(Ji,mi,"f",pi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}mi=Ji,Ji.STYLE_BLUE_STROKE=1,Ji.STYLE_GREEN_STROKE=2,Ji.STYLE_ORANGE_STROKE=3,Ji.STYLE_YELLOW_STROKE=4,Ji.STYLE_BLUE_STROKE_FILL=5,Ji.STYLE_GREEN_STROKE_FILL=6,Ji.STYLE_ORANGE_STROKE_FILL=7,Ji.STYLE_YELLOW_STROKE_FILL=8,Ji.STYLE_BLUE_STROKE_TRANSPARENT=9,Ji.STYLE_GREEN_STROKE_TRANSPARENT=10,Ji.STYLE_ORANGE_STROKE_TRANSPARENT=11,Ji.USER_START_STYLE_ID=1024,pi={value:new Map([[Ji.STYLE_BLUE_STROKE,{id:Ji.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_GREEN_STROKE,{id:Ji.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_ORANGE_STROKE,{id:Ji.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_YELLOW_STROKE,{id:Ji.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_BLUE_STROKE_FILL,{id:Ji.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_GREEN_STROKE_FILL,{id:Ji.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_ORANGE_STROKE_FILL,{id:Ji.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_YELLOW_STROKE_FILL,{id:Ji.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_BLUE_STROKE_TRANSPARENT,{id:Ji.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_GREEN_STROKE_TRANSPARENT,{id:Ji.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ji.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Ji.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},_i={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(Ie.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(Ie.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),Ie.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},Ie.Object.prototype.transparentCorners=!1,Ie.Object.prototype.cornerSize=20,Ie.Object.prototype.touchCornerSize=100,Ie.Object.prototype.cornerColor="rgb(254,142,20)",Ie.Object.prototype.cornerStyle="circle",Ie.Object.prototype.strokeUniform=!0,Ie.Object.prototype.hasBorders=!1,Ie.Canvas.prototype.containerClass="",Ie.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=Ie.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},Ie.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();Ie.util.addListener(Ie.document,"touchend",this._onTouchEnd,{passive:!1}),Ie.util.addListener(Ie.document,"touchmove",this._onMouseMove,{passive:!1}),Ie.util.removeListener(i,r+"down",this._onMouseDown)},Ie.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?Ie.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class Qi{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){let r,n;switch(this.mapMediaType_Style=new Map,this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=t.getFabricCanvas():(this.fabricCanvas=new Ie.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),this.fabricCanvas.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=e,e){case Qi.DDN_LAYER_ID:r=Ji.getDrawingStyle(Ji.STYLE_BLUE_STROKE),n=Ji.getDrawingStyle(Ji.STYLE_BLUE_STROKE_FILL);break;case Qi.DBR_LAYER_ID:r=Ji.getDrawingStyle(Ji.STYLE_ORANGE_STROKE),n=Ji.getDrawingStyle(Ji.STYLE_ORANGE_STROKE_FILL);break;case Qi.DLR_LAYER_ID:r=Ji.getDrawingStyle(Ji.STYLE_GREEN_STROKE),n=Ji.getDrawingStyle(Ji.STYLE_GREEN_STROKE_FILL);break;default:r=Ji.getDrawingStyle(Ji.STYLE_YELLOW_STROKE),n=Ji.getDrawingStyle(Ji.STYLE_YELLOW_STROKE_FILL)}for(let t of Pe.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(t){return t.styleId?t.styleId:this.mapType_StateAndStyleId.get(t._mediaType)[t.styleSelector]}_getItemCurrentStyle(t){if(t.styleId)return Ji.getDrawingStyle(t.styleId);return Ji.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=Ji.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Ji.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=Ji.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,Ji.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Ji.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Pe))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Pe.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Ji.getDrawingStyle(t.styleId);else{s=Ji.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Ji.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,Ji.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Pe.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Ji.getDrawingStyle(t.styleId);else{s=Ji.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Ji.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,Ji.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=Pe.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=Pe.arrStyleSelectors;const r=Ji.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&Ce.DIMT_RECTANGLE&&r.push("rect"),i&Ce.DIMT_QUADRILATERAL&&r.push("quad"),i&Ce.DIMT_TEXT&&r.push("text"),i&Ce.DIMT_ARC&&r.push("arc"),i&Ce.DIMT_IMAGE&&r.push("image"),i&Ce.DIMT_POLYGON&&r.push("polygon"),i&Ce.DIMT_LINE&&r.push("line");const n=[];e&Te.DIS_DEFAULT&&n.push("default"),e&Te.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Qi.DDN_LAYER_ID=1,Qi.DBR_LAYER_ID=2,Qi.DLR_LAYER_ID=3,Qi.USER_DEFINED_LAYER_BASE_ID=100,Qi.TIP_LAYER_ID=999;class $i{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Qi(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class tr extends di{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),vi.set(this,void 0),yi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&he(this,yi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),ae(this,vi,"f")),"f")}getDuration(){return ae(this,vi,"f")}}vi=new WeakMap,yi=new WeakMap;class er{constructor(){wi.add(this),Ei.set(this,void 0),Ci.set(this,void 0),Ti.set(this,void 0),bi.set(this,!0),this._drawingLayerManager=new $i}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=Qi.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Qi.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Qi.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ke(e=t)&&We(e.topLeftPoint)&&xe(e.width))||e.width<=0||!xe(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;he(this,Ei,JSON.parse(JSON.stringify(t)),"f"),ae(this,Ei,"f").coordinateBase||(ae(this,Ei,"f").coordinateBase="view"),he(this,Ti,t.duration,"f"),ae(this,wi,"m",Ai).call(this)}getTipConfig(){return ae(this,Ei,"f")?ae(this,Ei,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),he(this,bi,t,"f")}isTipVisible(){return ae(this,bi,"f")}updateTipMessage(t){if(!ae(this,Ei,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Ji.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Qi.TIP_LAYER_ID)||this._createDrawingLayer(Qi.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=ae(this,wi,"m",Si).call(this,t,ae(this,Ei,"f").topLeftPoint.x,ae(this,Ei,"f").topLeftPoint.y,ae(this,Ei,"f").width,ae(this,Ei,"f").coordinateBase,this._tipStyleId),ae(this,wi,"m",Ii).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",ae(this,bi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),ae(this,Ci,"f")&&clearTimeout(ae(this,Ci,"f")),ae(this,Ti,"f")>=0&&he(this,Ci,setTimeout((()=>{ae(this,wi,"m",xi).call(this)}),ae(this,Ti,"f")),"f")}}Ei=new WeakMap,Ci=new WeakMap,Ti=new WeakMap,bi=new WeakMap,wi=new WeakSet,Si=function(t,e,i,r,n,s){const o=new tr(t,e,i,r,s);return o.coordinateBase=n,o},Ii=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},xi=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},Ai=function(){if(!this._tip)return;const t=ae(this,Ei,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class ir extends HTMLElement{constructor(){super(),Ri.set(this,void 0);const t=document.createElement("template").content,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),he(this,Ri,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t.cloneNode(!0))}getWrapper(){return ae(this,Ri,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}Ri=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",ir);class rr extends HTMLElement{constructor(){super();const t=window._dce_default_template.content;this.attachShadow({mode:"open"}).appendChild(t.cloneNode(!0))}showScanLaser(){const t=this.shadowRoot.querySelector(".dce-scanlight");t&&(t.style.display="")}hideScanLaser(){const t=this.shadowRoot.querySelector(".dce-scanlight");t&&(t.style.display="none")}getElement(t){return this.shadowRoot.querySelector(t)}getVideoContainer(){return this.shadowRoot.querySelector(".dce-video-container")}getScanAreaEl(){return this.shadowRoot.querySelector(".dce-scanarea")}getScanLightEl(){return this.shadowRoot.querySelector(".dce-scanlight")}getLoadingBackgroundEl(){return this.shadowRoot.querySelector(".dce-bg-loading")}getCameraBackgroundEl(){return this.shadowRoot.querySelector(".dce-bg-camera")}getCameraSelectEl(){return this.shadowRoot.querySelector(".dce-sel-camera")}getResolutionSelectEl(){return this.shadowRoot.querySelector(".dce-sel-resolution")}getResolutionOptionEl(){return this.shadowRoot.querySelector(".dce-opt-gotResolution")}getCloseBtnEl(){return this.shadowRoot.querySelector(".dce-btn-close")}getDLRSelectEl(){return this.shadowRoot.querySelector(".dlr-sel-minletter")}getDLROptionEl(){return this.shadowRoot.querySelector(".dlr-opt-gotMinLtr")}}class nr extends er{static get engineResourcePath(){return ht.engineResourcePaths.dce}static set defaultUIElementURL(t){nr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=nr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",nr.engineResourcePath)}static async createInstance(t){customElements.get(nr.uiComponentName)||customElements.define(nr.uiComponentName,rr);const e=new nr;return await e.setUIElement(t||nr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==ae(this,Ui,"f")){if(he(this,Ui,t,"f"),ae(this,Oi,"m",Wi).call(this))he(this,Fi,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!ae(this,Fi,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(fe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),he(this,Fi,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}ae(this,Oi,"m",Wi).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return ae(this,Ui,"f")}get disposed(){return ae(this,Gi,"f")}constructor(){super(),Oi.add(this),Di.set(this,void 0),Li.set(this,void 0),Mi.set(this,void 0),this.containerClassName="dce-video-container",Fi.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,Pi.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,ki.set(this,!1),Bi.set(this,!1),Ni.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{ae(this,Oi,"m",zi).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&ae(this,Oi,"m",Xi).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{nr._onLog&&nr._onLog("window resize event triggered."),ae(this,Ni,"f").width===document.documentElement.clientWidth&&ae(this,Ni,"f").height===document.documentElement.clientHeight||(ae(this,Ni,"f").width=document.documentElement.clientWidth,ae(this,Ni,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Ui.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!ae(this,Oi,"m",Wi).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},this.extraBindings=[],ji.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>nr._transformCoordinates(t,i,r,n,s,o,a)));const c=new Ki({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),ae(this,ji,"f").push(c)};let m,p;for(let t of a)switch(t.type){case lt.CRIT_ORIGINAL_IMAGE:break;case lt.CRIT_BARCODE:m=this.getDrawingLayer(Qi.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Ji.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case lt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Qi.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Ji.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case lt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Qi.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Ji.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case lt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Qi.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Ji.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case lt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},Gi.set(this,!1),this.eventHandler=new Ke,this.eventHandler.on("content:updated",(()=>{ae(this,Di,"f")&&clearTimeout(ae(this,Di,"f")),he(this,Di,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{ae(this,Li,"f")&&clearTimeout(ae(this,Li,"f")),he(this,Li,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){t instanceof HTMLTemplateElement?(window._dce_default_template=t,this.UIElement=new rr):this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if(e="string"==typeof t?await $e(t):t,e instanceof HTMLDivElement&&0==e.childElementCount){const t=await $e(nr.defaultUIElementURL);t instanceof HTMLTemplateElement?(window._dce_default_template=t,e.append(new rr)):e.append(t),this._setUIElement(e)}else this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let e,i=this.UIElement;if(i instanceof rr?e=i.getElement(`.${this.containerClassName}`):i instanceof HTMLDivElement&&1===i.childElementCount&&i.firstElementChild instanceof rr?(e=i.firstElementChild.getElement(`.${this.containerClassName}`),i=i.firstElementChild):e=i.classList.contains(this.containerClassName)?i:i.querySelector(`.${this.containerClassName}`),!e)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new ir,e.appendChild(this._innerComponent),ae(this,Oi,"m",Wi).call(this));else{const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(fe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),he(this,Fi,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(i instanceof rr?(this._selRsl=i.getElement(".dce-sel-resolution"),this._selMinLtr=i.getElement(".dlr-sel-minletter"),this._divScanArea=i.getElement(".dce-scanarea"),this._divScanLight=i.getElement(".dce-scanlight"),this._bgLoading=i.getElement(".dce-bg-loading"),this._bgCamera=i.getElement(".dce-bg-camera"),this._selCam=i.getElement(".dce-sel-camera"),this._optGotRsl=i.getElement(".dce-opt-gotResolution"),this._btnClose=i.getElement(".dce-btn-close"),this._optGotMinLtr=i.getElement(".dlr-opt-gotMinLtr")):(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr")),this._selRsl&&(this._hideDefaultSelection||ae(this,Oi,"m",Wi).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||ae(this,Oi,"m",Wi).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||ae(this,Oi,"m",zi).call(this),ae(this,Oi,"m",Wi).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),ae(this,Oi,"m",Wi).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;nr._onLog&&nr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const e=null===(t=this._innerComponent)||void 0===t?void 0:t.getWrapper();e&&this._resizeObserver.observe(e)}ae(this,Ni,"f").width=document.documentElement.clientWidth,ae(this,Ni,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;ae(this,Oi,"m",Wi).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),ae(this,Oi,"m",zi).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,he(this,Fi,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(!this._selCam)return;let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"))}getVideoElement(){return ae(this,Fi,"f")}isVideoLoaded(){return!!ae(this,Fi,"f")&&4==ae(this,Fi,"f").readyState}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!ae(this,Fi,"f"))return;if(ae(this,Fi,"f").style.objectFit=t,ae(this,Oi,"m",Wi).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}ae(this,Oi,"m",Zi).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(ae(this,Oi,"m",Wi).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=ae(this,Fi,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=ae(this,Fi,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=Xe.convert(this.scanRegion,t.width,t.height);he(this,Pi,e,"f"),ae(this,Mi,"f")&&clearTimeout(ae(this,Mi,"f")),he(this,Mi,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}ae(this,Oi,"m",Vi).call(this,t,e),ae(this,Oi,"m",Zi).call(this,t,e)}),0),"f")}getConvertedRegion(){return ae(this,Pi,"f")}setScanRegion(t){if(null!=t&&!Ue(t)&&!Ye(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=ae(this,Fi,"f").videoWidth,i=ae(this,Fi,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=ae(this,Fi,"f").videoWidth,e=ae(this,Fi,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),ae(this,ji,"f").length=0}dispose(){this._unbindUI(),delete window._dce_default_template,this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function sr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function or(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}Di=new WeakMap,Li=new WeakMap,Mi=new WeakMap,Fi=new WeakMap,Pi=new WeakMap,ki=new WeakMap,Bi=new WeakMap,Ni=new WeakMap,Ui=new WeakMap,ji=new WeakMap,Gi=new WeakMap,Oi=new WeakSet,Wi=function(){return"disabled"!==this._singleFrameMode},Vi=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},Yi=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Hi=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Xi=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},zi=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Zi=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===dr.browser&&dr.version>13||"OPR"===dr.browser&&dr.version>43||"Edge"===dr.browser&&dr.version,"function"==typeof SuppressedError&&SuppressedError;class mr{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return mr.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return mr.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return mr.multiply(t,[e,0,0,0,i,0,0,0,1])}}var pr,_r,vr,yr,wr,Er,Cr,Tr,br,Sr,Ir,xr,Ar,Rr,Or,Dr,Lr,Mr,Fr,Pr,kr,Br,Nr,Ur,jr,Gr,Wr,Vr,Yr,Hr,Xr,zr,Zr,Kr,qr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(pr||(pr={}));class mn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(gr(mn,_r,!1,"f",vr),!1):(gr(mn,_r,!0,"f",vr),!0)}get disposed(){return fr(this,br,"f")}constructor(){yr.set(this,pr.RGBA),wr.set(this,null),Er.set(this,null),Cr.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Tr.set(this,null),br.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==fr(mn,_r,"f",vr)&&mn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!fr(mn,_r,"f",vr))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;mn._onLog&&(o=Date.now(),mn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=pr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!fr(mn,_r,"f",vr)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){mn._onLog&&mn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);gr(this,Er,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),gr(this,Cr,e(t),"f"),gr(this,wr,i(t),"f"),gr(this,yr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[pr.GREY,pr.GREY32].includes(p)?1:0);let m,_,v=mr.translate(mr.identity(),-1,-1);v=mr.scale(v,2,2),v=mr.scale(v,1/t.canvas.width,1/t.canvas.height),m=mr.translate(v,u,d),m=mr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=mr.translate(mr.identity(),a/i,h/r),_=mr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,fr(this,wr,"f"),e),v(t,fr(this,Er,"f"),fr(this,Cr,"f"),fr(this,wr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){mn._onLog&&mn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return mn._onLog&&mn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===pr.GREY?pr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return mn._onLog&&mn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(mn._onLog&&(n=Date.now(),mn._onLog("transformPixelFormat(), START: "+n)),e===i)return mn._onLog&&mn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[pr.RGBA,pr.RBGA,pr.GRBA,pr.GBRA,pr.BRGA,pr.BGRA];if(o.includes(e))if(i===pr.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;mn._onLog&&(s=Date.now(),mn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=pr.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),fr(mn,_r,"f",vr)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){mn._onLog&&mn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===pr.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||n.apply(i.target,r)}),0);else try{s=await n.apply(i.target,r)}catch(t){}if(!0===s)break}}}dispose(){or(this,Ir,!0,"f")}}Sr=new WeakMap,Ir=new WeakMap;const _n=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class vn{static get version(){return"2.0.2"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(dr.OS))return vn.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(dr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(e){vn._onLog&&vn._onLog("1st play error: "+((null==e?void 0:e.message)||e)),await m;try{await t.play(),h()}catch(t){vn._onLog&&vn._onLog("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!sr(this,jr,"f"))return"closed";if("pending"===sr(this,jr,"f"))return"opening";if("fulfilled"===sr(this,jr,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?vn.isStorageAvailable("localStorage")?or(this,kr,!0,"f"):(or(this,kr,!1,"f"),console.warn("Local storage is unavailable")):or(this,kr,!1,"f")}get ifSaveLastUsedCamera(){return sr(this,kr,"f")}get isVideoPlaying(){return!(!sr(this,Rr,"f")||sr(this,Rr,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=sr(this,Xr,"f"))||void 0===e||e.removeEventListener("click",sr(this,Hr,"f")),null===(i=sr(this,Xr,"f"))||void 0===i||i.removeEventListener("touchend",sr(this,Hr,"f")),null===(r=sr(this,Xr,"f"))||void 0===r||r.removeEventListener("touchmove",sr(this,Yr,"f")),or(this,Xr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(dr.OS)?(t.addEventListener("touchend",sr(this,Hr,"f")),t.addEventListener("touchmove",sr(this,Yr,"f"))):t.addEventListener("click",sr(this,Hr,"f")))}get tapFocusEventBoundEl(){return sr(this,Xr,"f")}get disposed(){return sr(this,en,"f")}constructor(t){var e,i;Ar.add(this),Rr.set(this,null),Or.set(this,void 0),Dr.set(this,(()=>{"opened"===this.state&&sr(this,qr,"f").fire("resumed",null,{target:this,async:!0})})),Lr.set(this,(()=>{sr(this,qr,"f").fire("paused",null,{target:this,async:!1})})),Mr.set(this,void 0),Fr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Pr.set(this,void 0),kr.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,Br.set(this,void 0),Nr.set(this,!0),Ur.set(this,void 0),jr.set(this,void 0),Gr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},Wr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(sr(this,Rr,"f")).objectFit,s=this.getResolution(),o=sr(this,Rr,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=sr(this,Rr,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},Vr.set(this,!1),Yr.set(this,(()=>{or(this,Vr,!0,"f")})),Hr.set(this,(async t=>{var e;if(sr(this,Vr,"f"))return void or(this,Vr,!1,"f");if(!sr(this,Wr,"f"))return;if(!this.isVideoPlaying)return;if(!sr(this,Or,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;vn._onLog&&(c=Date.now());try{await sr(this,Ar,"m",dn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(vn._onLog)throw vn._onLog(t),t}vn._onLog&&vn._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;vn._onLog&&vn._onLog("Back to continuous focus."),null===(t=sr(this,Or,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),sr(this,qr,"f").fire("tapfocus",null,{target:this,async:!0})})),Xr.set(this,null),zr.set(this,1),Zr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!sr(this,Rr,"f"))return;const t=sr(this,zr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)sr(this,Rr,"f").style.transform="";else{const e=window.getComputedStyle(sr(this,Rr,"f")).objectFit,i=sr(this,Rr,"f").videoWidth,r=sr(this,Rr,"f").videoHeight,{width:n,height:s}=sr(this,Rr,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-sr(this,Zr,"f").x),c=h*(1-1/t)*(r/2-sr(this,Zr,"f").y);sr(this,Rr,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},Kr.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===pr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(vn._onLog&&vn._onLog("document visible. video paused: "+(null===(t=sr(this,Rr,"f"))||void 0===t?void 0:t.paused)),sr(this,$r,"f")&&sr(this,Rr,"f")&&this.videoSrc&&"opened"===this.state)return void this.resume().catch((()=>{}));if(!this._mediaStream)return;if(this._mediaStream.active&&sr(this,Or,"f"))if(sr(this,Or,"f").muted&&["iPhone","iPad","Mac"].includes(dr.OS)){if(dr.version>=17)return void vn.playVideo(sr(this,Rr,"f"),this._mediaStream,this.cameraOpenTimeout);await sr(this,Ar,"m",an).call(this)}else sr(this,$r,"f")&&this.resume().catch((()=>{}));else await sr(this,Ar,"m",an).call(this)}else if("hidden"===document.visibilityState&&(vn._onLog&&vn._onLog("document hidden. video paused: "+(null===(e=sr(this,Rr,"f"))||void 0===e?void 0:e.paused)),["iPhone","iPad","Mac"].includes(dr.OS)?or(this,$r,!0,"f"):or(this,$r,this.isVideoPlaying,"f"),this.isVideoLoaded()&&"opened"==this.state)){if(["iPhone","iPad","Mac"].includes(dr.OS)&&dr.version>=17)return;this.pause()}})),en.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{vn.onWarning&&vn.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),or(this,qr,new pn,"f"),this.imageDataGetter=new mn,document.addEventListener("visibilitychange",sr(this,tn,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",sr(this,Dr,"f")),t.addEventListener("pause",sr(this,Lr,"f")),or(this,Rr,t,"f")}getVideoEl(){return sr(this,Rr,"f")}releaseVideoEl(){var t,e;null===(t=sr(this,Rr,"f"))||void 0===t||t.removeEventListener("play",sr(this,Dr,"f")),null===(e=sr(this,Rr,"f"))||void 0===e||e.removeEventListener("pause",sr(this,Lr,"f")),or(this,Rr,null,"f")}isVideoLoaded(){return!!sr(this,Rr,"f")&&4==sr(this,Rr,"f").readyState}async open(){if(sr(this,Ur,"f")&&!sr(this,Nr,"f")){if("pending"===sr(this,jr,"f"))return sr(this,Ur,"f");if("fulfilled"===sr(this,jr,"f"))return}sr(this,qr,"f").fire("before:open",null,{target:this}),await sr(this,Ar,"m",an).call(this),sr(this,qr,"f").fire("opened",null,{target:this,async:!0}),sr(this,qr,"f").fire("played",null,{target:this,async:!0})}async close(){if("closed"===this.state)return;sr(this,qr,"f").fire("before:close",null,{target:this});const t=sr(this,Ur,"f");if(sr(this,Ar,"m",ln).call(this),t&&"pending"===sr(this,jr,"f")){try{await t}catch(t){}if(!1===sr(this,Nr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}or(this,Ur,null,"f"),or(this,jr,null,"f"),sr(this,qr,"f").fire("closed",null,{target:this,async:!0})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");sr(this,Rr,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await sr(this,Rr,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof sr(this,Mr,"f").video&&(sr(this,Mr,"f").video={}),delete sr(this,Mr,"f").video.facingMode,sr(this,Mr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&sr(this,Nr,"f"))){sr(this,qr,"f").fire("before:camera:change",[],{target:this,async:!1}),await sr(this,Ar,"m",hn).call(this);try{this.resetSoftwareScale()}catch(t){}return sr(this,Fr,"f")}}async switchToFrontCamera(t){if("object"!=typeof sr(this,Mr,"f").video&&(sr(this,Mr,"f").video={}),(null==t?void 0:t.resolution)&&(sr(this,Mr,"f").video.width={ideal:t.resolution.width},sr(this,Mr,"f").video.height={ideal:t.resolution.height}),delete sr(this,Mr,"f").video.deviceId,sr(this,Mr,"f").video.facingMode={exact:"user"},or(this,Pr,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&sr(this,Nr,"f"))){sr(this,qr,"f").fire("before:camera:change",[],{target:this,async:!1}),sr(this,Ar,"m",hn).call(this);try{this.resetSoftwareScale()}catch(t){}return sr(this,Fr,"f")}}getCamera(){var t;if(sr(this,Fr,"f"))return sr(this,Fr,"f");{let e=(null===(t=sr(this,Mr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof sr(this,Mr,"f").video&&(sr(this,Mr,"f").video={}),i?(sr(this,Mr,"f").video.width={exact:t},sr(this,Mr,"f").video.height={exact:e}):(sr(this,Mr,"f").video.width={ideal:t},sr(this,Mr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&sr(this,Nr,"f"))return null;sr(this,qr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await sr(this,Ar,"m",hn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&sr(this,Rr,"f"))return{width:sr(this,Rr,"f").videoWidth,height:sr(this,Rr,"f").videoHeight};if(sr(this,Or,"f")){const t=sr(this,Or,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:sr(this,Rr,"f").videoWidth,height:sr(this,Rr,"f").videoHeight};{const t={width:0,height:0};let e=sr(this,Mr,"f").video.width||0,i=sr(this,Mr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=sr(this,Qr,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=sr(this,Fr,"f"))||void 0===u?void 0:u.deviceId;let e=sr(this,Qr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],sr(this,Qr,"f").set(d,e),or(this,Gr,!0,"f");try{for(let t of this.detectedResolutions){await sr(this,Or,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),sr(this,Ar,"m",nn).call(this);const i=sr(this,Or,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw sr(this,Ar,"m",ln).call(this),or(this,Gr,!1,"f"),t}try{await sr(this,Ar,"m",an).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{or(this,Gr,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=sr(this,Mr,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=sr(this,Mr,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=sr(this,Mr,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=sr(this,Qr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],sr(this,Qr,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");or(this,Mr,JSON.parse(JSON.stringify(t)),"f"),or(this,Pr,null,"f"),e&&sr(this,Ar,"m",hn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(sr(this,Mr,"f")))}resetMediaStreamConstraints(){or(this,Mr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return sr(this,Or,"f").getCapabilities?sr(this,Or,"f").getCapabilities():{}}getCameraSettings(){if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return sr(this,Or,"f").getSettings()}async turnOnTorch(){if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await sr(this,Or,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await sr(this,Or,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=_n(t,r.min,r.step,r.max)),await sr(this,Or,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=_n(t,r.min,r.step,r.max)),await sr(this,Or,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await sr(this,Or,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=_n(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await sr(this,Or,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await sr(this,Ar,"m",dn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await sr(this,Or,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){or(this,Wr,!0,"f")}disableTapToFocus(){or(this,Wr,!1,"f")}isTapToFocusEnabled(){return sr(this,Wr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?sr(this,Ar,"m",fn).call(this,t.centerPoint):this.resetScaleCenter();try{if(sr(this,Ar,"m",gn).call(this,sr(this,Zr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*sr(this,zr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!sr(this,Or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=_n(t,r.min,r.step,r.max)),await sr(this,Or,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&sr(this,Ar,"m",fn).call(this,e),or(this,zr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return sr(this,zr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();or(this,Zr,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(sr(this,Gr,"f"))return null;const e=Date.now();vn._onLog&&vn._onLog("getFrameData() START: "+e);const i=sr(this,Rr,"f").videoWidth,r=sr(this,Rr,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=pr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=sr(this,zr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=sr(this,Zr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(sr(this,Rr,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return vn._onLog&&vn._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:sr(this,Kr,"f")}}on(t,e){if(!sr(this,Jr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);sr(this,qr,"f").on(t,e)}off(t,e){sr(this,qr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),sr(this,qr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",sr(this,tn,"f")),or(this,en,!0,"f")}}var yn,wn,En,Cn,Tn,bn,Sn,In,xn,An,Rn,On,Dn,Ln,Mn,Fn,Pn,kn,Bn,Nn,Un,jn,Gn,Wn,Vn,Yn,Hn,Xn,zn,Zn,Kn,qn,Jn;Rr=new WeakMap,Or=new WeakMap,Dr=new WeakMap,Lr=new WeakMap,Mr=new WeakMap,Fr=new WeakMap,Pr=new WeakMap,kr=new WeakMap,Br=new WeakMap,Nr=new WeakMap,Ur=new WeakMap,jr=new WeakMap,Gr=new WeakMap,Wr=new WeakMap,Vr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,Zr=new WeakMap,Kr=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,tn=new WeakMap,en=new WeakMap,Ar=new WeakSet,rn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(sr(this,Pr,"f"))delete t.video.facingMode,t.video.deviceId={exact:sr(this,Pr,"f")};else if(this.ifSaveLastUsedCamera&&vn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(dr.OS)?(await this._getCameras(!1),sr(this,Ar,"m",nn).call(this),e=vn.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(dr.OS)||(await this._getCameras(!1),sr(this,Ar,"m",nn).call(this),e=vn.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},nn=function(){if(sr(this,Nr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},sn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{vn._onLog&&vn._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),sr(this,Ar,"m",nn).call(this));try{vn._onLog&&vn._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),sr(this,Ar,"m",nn).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,vn._onLog&&vn._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},on=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),or(this,Or,null,"f")},an=async function(){or(this,Nr,!1,"f");const t=or(this,Br,Symbol(),"f");if(sr(this,Ur,"f")&&"pending"===sr(this,jr,"f")){try{await sr(this,Ur,"f")}catch(t){}sr(this,Ar,"m",nn).call(this)}if(t!==sr(this,Br,"f"))return;const e=or(this,Ur,(async()=>{or(this,jr,"pending","f");try{if(this.videoSrc){if(!sr(this,Rr,"f"))throw new Error("'videoEl' should be set.");await vn.playVideo(sr(this,Rr,"f"),this.videoSrc,this.cameraOpenTimeout),sr(this,Ar,"m",nn).call(this)}else{let t=await sr(this,Ar,"m",rn).call(this);sr(this,Ar,"m",on).call(this);let e=await sr(this,Ar,"m",sn).call(this,t);await this._getCameras(!1),sr(this,Ar,"m",nn).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=sr(this,Mr,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(sr(this,Pr,"f")||this.ifSaveLastUsedCamera&&vn.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=vn.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await sr(this,Ar,"m",sn).call(this,t),sr(this,Ar,"m",nn).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(or(this,Pr,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&vn.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",sr(this,Pr,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),sr(this,Rr,"f")&&(await vn.playVideo(sr(this,Rr,"f"),e,this.cameraOpenTimeout),sr(this,Ar,"m",nn).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&or(this,Or,s[0],"f"),or(this,Fr,n,"f")}}catch(t){throw sr(this,Ar,"m",ln).call(this),or(this,jr,null,"f"),t}or(this,jr,"fulfilled","f")})(),"f");return e},hn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=sr(this,Fr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await sr(this,Ar,"m",an).call(this);const r=this.getResolution();e&&e!==sr(this,Fr,"f").deviceId&&sr(this,qr,"f").fire("camera:changed",[sr(this,Fr,"f").deviceId,e],{target:this,async:!0}),i.width==r.width&&i.height==r.height||sr(this,qr,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!0}),sr(this,qr,"f").fire("played",null,{target:this,async:!0})},ln=function(){sr(this,Ar,"m",on).call(this),or(this,Fr,null,"f"),sr(this,Rr,"f")&&(sr(this,Rr,"f").srcObject=null,this.videoSrc&&(sr(this,Rr,"f").pause(),sr(this,Rr,"f").currentTime=0)),or(this,Nr,!0,"f");try{this.resetSoftwareScale()}catch(t){}},cn=async function t(e,i){const r=t=>{if(!sr(this,Or,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){sr(this,Or,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=_n(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await sr(this,Or,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();if(s>=l.width||o>=l.height)throw new Error("Invalid area.");s+a>l.width&&(a=l.width-s),o+h>l.height&&(h=l.height-o),s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(sr(this,Rr,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:pr.RGBA,bufferContainer:d}))return sr(this,Ar,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await sr(this,Ar,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await sr(this,Ar,"m",cn).call(this,e,c);if(a>h)return await sr(this,Ar,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await sr(this,Ar,"m",t).call(this,e,o,a,c,h);let u=await sr(this,Ar,"m",cn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==sr(this,zr,"f")){const t=sr(this,zr,"f"),e=sr(this,Zr,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=_n(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=_n(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=_n(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await sr(this,Ar,"m",cn).call(this,t,s),a=await sr(this,Ar,"m",cn).call(this,t,n),h=await sr(this,Ar,"m",cn).call(this,t,r);if(a>h&&ho&&a>o){let e=await sr(this,Ar,"m",cn).call(this,t,i);const n=await sr(this,Ar,"m",un).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await sr(this,Ar,"m",un).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},fn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");or(this,Zr,{x:i,y:r},"f")},gn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},vn.browserInfo=dr,vn.onWarning=null===(xr=null===window||void 0===window?void 0:window.console)||void 0===xr?void 0:xr.warn;class Qn{constructor(t){yn.add(this),wn.set(this,void 0),En.set(this,0),Cn.set(this,void 0),Tn.set(this,0),bn.set(this,!1),he(this,wn,t,"f")}startCharging(){ae(this,bn,"f")||(Qn._onLog&&Qn._onLog("start charging."),ae(this,yn,"m",In).call(this),he(this,bn,!0,"f"))}stopCharging(){ae(this,Cn,"f")&&clearTimeout(ae(this,Cn,"f")),ae(this,bn,"f")&&(Qn._onLog&&Qn._onLog("stop charging."),he(this,En,Date.now()-ae(this,Tn,"f"),"f"),he(this,bn,!1,"f"))}}wn=new WeakMap,En=new WeakMap,Cn=new WeakMap,Tn=new WeakMap,bn=new WeakMap,yn=new WeakSet,Sn=function(){ht.cfd(1),Qn._onLog&&Qn._onLog("charge 1.")},In=function t(){0==ae(this,En,"f")&&ae(this,yn,"m",Sn).call(this),he(this,Tn,Date.now(),"f"),ae(this,Cn,"f")&&clearTimeout(ae(this,Cn,"f")),he(this,Cn,setTimeout((()=>{he(this,En,0,"f"),ae(this,yn,"m",t).call(this)}),ae(this,wn,"f")-ae(this,En,"f")),"f")};const $n=new Map([[s.IPF_GRAYSCALED,pr.GREY],[s.IPF_ABGR_8888,pr.RGBA],[s.IPF_ARGB_8888,pr.BGRA]]),ts=new Map([[pr.GREY,s.IPF_GRAYSCALED],[pr.RGBA,s.IPF_ABGR_8888],[pr.BGRA,s.IPF_ARGB_8888]]),es="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class is extends O{static set _onLog(t){he(is,An,t,"f",Rn),vn._onLog=t,Qn._onLog=t}static get _onLog(){return ae(is,An,"f",Rn)}static async detectEnvironment(){return await(async()=>({wasm:ge,worker:me,getUserMedia:pe,camera:await _e(),browser:fe.browser,version:fe.version,OS:fe.OS}))()}static async testCameraAccess(){const t=await vn.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof nr))throw new TypeError("Invalid view.");if(null===(e=rt.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=rt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await ht.loadWasm(["license"]),await rt.license.dynamsoft()}const r=new is(t);return is.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{is.onWarning&&is.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{is.onWarning&&is.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return ae(this,On,"f").getVideoEl()}set videoSrc(t){if(!ae(this,On,"f"))throw new Error("Camera manager is null.");ae(this,Dn,"f")&&(ae(this,Dn,"f")._hideDefaultSelection=!0),ae(this,On,"f").videoSrc=t}get videoSrc(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!ae(this,On,"f"))throw new Error("Camera manager is null.");ae(this,On,"f").ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!ae(this,On,"f"))throw new Error("Camera manager is null.");ae(this,On,"f").ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!ae(this,On,"f"))throw new Error("Camera manager is null.");ae(this,On,"f").cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");he(this,Pn,t,"f")}get singleFrameMode(){return ae(this,Pn,"f")}get _isFetchingStarted(){return ae(this,Gn,"f")}get disposed(){return ae(this,Xn,"f")}constructor(t){if(super(),xn.add(this),On.set(this,void 0),Dn.set(this,void 0),Ln.set(this,"closed"),Mn.set(this,void 0),Fn.set(this,!1),Pn.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&ae(this,Dn,"f")&&!ae(this,Dn,"f").disposed&&await this.selectCamera(ae(this,Dn,"f")._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!ae(this,Dn,"f")||ae(this,Dn,"f").disposed)return;let t,e;if(ae(this,Dn,"f")._selRsl&&-1!=ae(this,Dn,"f")._selRsl.selectedIndex){let i=ae(this,Dn,"f")._selRsl.options[ae(this,Dn,"f")._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&ae(this,Dn,"f")&&!ae(this,Dn,"f").disposed&&this.close()},kn.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=ae(this,On,"f").imageDataGetter.getImageData(t,e,i,s,{pixelFormat:$n.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===pr.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:ts.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:gt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:ae(this,Bn,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=ae(this,Dn,"f")?ae(this,Dn,"f").getConvertedRegion():Xe.convert(ae(this,Un,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=ae(this,kn,"f").call(this,t,t.width,t.height,e);ae(this,Mn,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},Bn.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===s.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=ae(this,On,"f").getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");ae(this,Dn,"f")&&!ae(this,Dn,"f").disposed?(this.video.style.transform=1===t?"":`scale(${t})`,ae(this,Dn,"f")._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(fe.OS)?ae(this,On,"f").setResolution(1280,720):ae(this,On,"f").setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&this.setCameraView(t),this._on("before:camera:change",(()=>{ae(this,Hn,"f").stopCharging();const t=ae(this,Dn,"f");t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=ae(this,Dn,"f");t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{ae(this,Hn,"f").stopCharging();const t=ae(this,Dn,"f");t&&t.disposed})),this._on("resumed",(()=>{const t=ae(this,Dn,"f");t&&t.disposed})),this._on("tapfocus",(()=>{ae(this,Vn,"f").tapToFocus&&ae(this,Hn,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(ae(this,xn,"m",zn).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;is._onLog&&(is._onLog("intermediateResultUnits:"),is._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===_t.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===_t.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(is._onLog&&(is._onLog("hasLocalizedBarcodes:"),is._onLog(h)),ae(this,Vn,"f").autoZoom||ae(this,Vn,"f").enhancedFocus)if(a)ae(this,Yn,"f").autoZoomInFrameArray.length=0,ae(this,Yn,"f").autoZoomOutFrameCount=0,ae(this,Yn,"f").frameArrayInIdealZoom.length=0,ae(this,Vn,"f").autoZoom&&ae(this,Vn,"f").enhancedFocus&&(ae(this,Yn,"f").nextActionInIdealZoom="focus"),ae(this,Yn,"f").autoFocusFrameArray.length=0,ae(this,Yn,"f").noIntermediateResultsCount=0;else{const e=async t=>{await this.setZoom(t),ae(this,Vn,"f").autoZoom&&ae(this,Hn,"f").startCharging()},a=async t=>{await this.setFocus(t),ae(this,Vn,"f").enhancedFocus&&ae(this,Hn,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-ae(this,Yn,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+ae(this,Yn,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-ae(this,Yn,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+ae(this,Yn,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}is._onLog&&(is._onLog("detectionArea:"),is._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=Je(a.y-i)>0&&Je(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(Qe([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Qe([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Qe([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Qe([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{nr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(is._debug&&ae(this,Dn,"f")){const t=this.__layer||(this.__layer=ae(this,Dn,"f")._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Ji.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new ci({points:i},e);t.addDrawingItems([n])}}}if(is._onLog&&(is._onLog("intersectedResults:"),is._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==es.BF_QR_CODE||t.possibleFormats==es.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==es.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{}))),ae(this,Yn,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=ae(this,Yn,"f").autoZoomInFrameLimit[1]){ae(this,Yn,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,ae(this,Yn,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/ae(this,Yn,"f").autoZoomInMaxTimes),ae(this,Yn,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(ae(this,Yn,"f").minValue,u),u=Math.min(ae(this,Yn,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(ae(this,Yn,"f").autoZoomInFrameArray.length=0,ae(this,Yn,"f").frameArrayInIdealZoom.push(!0),ae(this,Yn,"f").frameArrayInIdealZoom.splice(0,ae(this,Yn,"f").frameArrayInIdealZoom.length-ae(this,Yn,"f").frameLimitInIdealZoom[0]),ae(this,Yn,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=ae(this,Yn,"f").frameLimitInIdealZoom[1])if(ae(this,Yn,"f").frameArrayInIdealZoom.length=0,"focus"===ae(this,Yn,"f").nextActionInIdealZoom&&ae(this,Vn,"f").enhancedFocus){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}else{if("zoomOut"!==ae(this,Yn,"f").nextActionInIdealZoom&&ae(this,Vn,"f").enhancedFocus)throw new Error("Invalid action.");if(ae(this,Yn,"f").enableZoomOutInIdealZoom){r=ae(this,Yn,"f").autoZoomIdealArea[1]+ae(this,Yn,"f").autoZoomOutStepRate_2;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0));let l=Math.min(...i)*this.getZoomSettings().factor;l=Math.max(ae(this,Yn,"f").minValue,l),l=Math.min(ae(this,Yn,"f").maxValue,l);try{await e({factor:l})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer(),ae(this,Vn,"f").enhancedFocus&&(ae(this,Yn,"f").nextActionInIdealZoom="focus",a({mode:"continuous"}).catch((()=>{})))}}}if(!ae(this,Vn,"f").autoZoom&&ae(this,Vn,"f").enhancedFocus&&(ae(this,Yn,"f").autoFocusFrameArray.push(!0),ae(this,Yn,"f").autoFocusFrameArray.splice(0,ae(this,Yn,"f").autoFocusFrameArray.length-ae(this,Yn,"f").autoFocusFrameLimit[0]),ae(this,Yn,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=ae(this,Yn,"f").autoFocusFrameLimit[1])){ae(this,Yn,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(ae(this,Yn,"f").noIntermediateResultsCount++,ae(this,Vn,"f").autoZoom){if(ae(this,Yn,"f").autoZoomInFrameArray.push(!1),ae(this,Yn,"f").autoZoomInFrameArray.splice(0,ae(this,Yn,"f").autoZoomInFrameArray.length-ae(this,Yn,"f").autoZoomInFrameLimit[0]),ae(this,Yn,"f").autoZoomOutFrameCount++,ae(this,Yn,"f").frameArrayInIdealZoom.push(!1),ae(this,Yn,"f").frameArrayInIdealZoom.splice(0,ae(this,Yn,"f").frameArrayInIdealZoom.length-ae(this,Yn,"f").frameLimitInIdealZoom[0]),ae(this,Yn,"f").autoZoomOutFrameCount>=ae(this,Yn,"f").autoZoomOutFrameLimit){ae(this,Yn,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*ae(this,Yn,"f").autoZoomOutStepRate,ae(this,Yn,"f").autoZoomOutMinStep);r=Math.max(ae(this,Yn,"f").minValue,r),r=Math.min(ae(this,Yn,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}ae(this,Vn,"f").enhancedFocus&&(ae(this,Yn,"f").nextActionInIdealZoom="focus",a({mode:"continuous"}).catch((()=>{})))}!ae(this,Vn,"f").autoZoom&&ae(this,Vn,"f").enhancedFocus&&(ae(this,Yn,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},he(this,Hn,new Qn(1e4),"f")}setCameraView(t){if(!(t instanceof nr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(ae(this,Dn,"f")._hideDefaultSelection=!0),ae(this,xn,"m",zn).call(this)||ae(this,On,"f").setVideoEl(t.getVideoElement()),he(this,Dn,t,"f"),this.addListenerToView()}getCameraView(){return ae(this,Dn,"f")}releaseCameraView(){ae(this,Dn,"f")&&(this.removeListenerFromView(),ae(this,Dn,"f").disposed||(ae(this,Dn,"f")._singleFrameMode="disabled",ae(this,Dn,"f")._onSingleFrameAcquired=null,ae(this,Dn,"f")._hideDefaultSelection=!1),ae(this,On,"f").releaseVideoEl(),he(this,Dn,null,"f"))}addListenerToView(){if(!ae(this,Dn,"f"))return;if(ae(this,Dn,"f").disposed)throw new Error("'cameraView' has been disposed.");const t=ae(this,Dn,"f");ae(this,xn,"m",zn).call(this)||this.videoSrc||(t._innerComponent&&(ae(this,On,"f").tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!ae(this,Dn,"f")||ae(this,Dn,"f").disposed)return;const t=ae(this,Dn,"f");ae(this,On,"f").tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return ae(this,xn,"m",zn).call(this)?ae(this,Ln,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(ae(this,On,"f").state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=ae(this,Dn,"f");if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,ae(this,xn,"m",zn).call(this)?t._clickIptSingleFrameMode():(ae(this,On,"f").setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(ae(this,xn,"m",zn).call(this));else{try{await ae(this,On,"f").open()}catch(e){throw t&&t._stopLoading(),e}ae(this,Fn,"f")&&this.turnOnTorch().catch((()=>{}));const i=this.getResolution();e.width=i.width,e.height=i.height,e.deviceId=this.getSelectedCamera().deviceId}return he(this,Ln,"open","f"),t&&(t._innerComponent.style.display="",ae(this,xn,"m",zn).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),ae(this,On,"f")._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!0}),t.eventHandler.fire("videoEl:resized",null,{async:!0}))),ae(this,Mn,"f").fire("opened",null,{target:this,async:!0}),e}close(){const t=ae(this,Dn,"f");if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");this.stopFetching(),this.clearBuffer(),ae(this,xn,"m",zn).call(this)||ae(this,On,"f").close(),he(this,Ln,"closed","f"),ae(this,Hn,"f").stopCharging(),t&&(t._innerComponent.style.display="none",ae(this,xn,"m",zn).call(this)&&t._innerComponent.removeElement("content"),t._stopLoading()),ae(this,Mn,"f").fire("closed",null,{target:this,async:!0})}pause(){if(ae(this,xn,"m",zn).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");ae(this,On,"f").pause()}isPaused(){var t;return!ae(this,xn,"m",zn).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(ae(this,xn,"m",zn).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await ae(this,On,"f").resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await ae(this,On,"f").setCamera(e),he(this,Fn,!1,"f");const i=this.getResolution(),r=ae(this,Dn,"f");return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),ae(this,On,"f")._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return ae(this,On,"f").getCamera()}async getAllCameras(){return ae(this,On,"f").getCameras()}async setResolution(t){await ae(this,On,"f").setResolution(t.width,t.height),ae(this,Fn,"f")&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=ae(this,Dn,"f");return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return ae(this,On,"f").getResolution()}getAvailableResolutions(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ae(this,Mn,"f").on(t,e):ae(this,On,"f").on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ae(this,Mn,"f").off(t,e):ae(this,On,"f").off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=ae(this,On,"f"))||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return ae(this,On,"f").getCameraSettings()}async turnOnTorch(){var t;if(ae(this,xn,"m",zn).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");await(null===(t=ae(this,On,"f"))||void 0===t?void 0:t.turnOnTorch()),he(this,Fn,!0,"f")}async turnOffTorch(){var t;if(ae(this,xn,"m",zn).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=ae(this,On,"f"))||void 0===t?void 0:t.turnOffTorch()),he(this,Fn,!1,"f")}async setColorTemperature(t){if(ae(this,xn,"m",zn).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await ae(this,On,"f").setColorTemperature(t,!0)}getColorTemperature(){return ae(this,On,"f").getColorTemperature()}async setExposureCompensation(t){var e;if(ae(this,xn,"m",zn).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=ae(this,On,"f"))||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e;if(ae(this,xn,"m",zn).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=ae(this,On,"f"))||void 0===e?void 0:e.setZoom(t))}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(ae(this,xn,"m",zn).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=ae(this,On,"f"))||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(ae(this,xn,"m",zn).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=ae(this,On,"f"))||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(ae(this,xn,"m",zn).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=ae(this,On,"f"))||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=ae(this,On,"f"))||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){ae(this,Yn,"f").minValue=t.min,ae(this,Yn,"f").maxValue=t.max}getAutoZoomRange(){return{min:ae(this,Yn,"f").minValue,max:ae(this,Yn,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=rt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==ht.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&be.EF_ENHANCED_FOCUS&&(ae(this,Vn,"f").enhancedFocus=!0),t&be.EF_AUTO_ZOOM&&(ae(this,Vn,"f").autoZoom=!0),t&be.EF_TAP_TO_FOCUS&&(ae(this,Vn,"f").tapToFocus=!0,ae(this,On,"f").enableTapToFocus())}disableEnhancedFeatures(t){t&be.EF_ENHANCED_FOCUS&&(ae(this,Vn,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&be.EF_AUTO_ZOOM&&(ae(this,Vn,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&be.EF_TAP_TO_FOCUS&&(ae(this,Vn,"f").tapToFocus=!1,ae(this,On,"f").disableTapToFocus()),ae(this,xn,"m",Kn).call(this)&&ae(this,xn,"m",Zn).call(this)||ae(this,Hn,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!Ue(t)&&!Ye(t))throw TypeError("Invalid 'region'.");he(this,Un,t?JSON.parse(JSON.stringify(t)):null,"f"),ae(this,Dn,"f")&&!ae(this,Dn,"f").disposed&&ae(this,Dn,"f").setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),ae(this,Dn,"f")&&!ae(this,Dn,"f").disposed&&(null===t?ae(this,Dn,"f").setScanRegionMaskVisible(!1):ae(this,Dn,"f").setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(ae(this,Un,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");he(this,Nn,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!ae(this,On,"f").isVideoLoaded()||ae(this,xn,"m",zn).call(this))}startFetching(){if(ae(this,xn,"m",zn).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");ae(this,Gn,"f")||(he(this,Gn,!0,"f"),ae(this,xn,"m",qn).call(this))}stopFetching(){ae(this,Gn,"f")&&(is._onLog&&is._onLog("DCE: stop fetching loop: "+Date.now()),ae(this,Wn,"f")&&clearTimeout(ae(this,Wn,"f")),he(this,Gn,!1,"f"))}fetchImage(){if(ae(this,xn,"m",zn).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Xe.convert(ae(this,Un,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=ae(this,On,"f").getFrameData({position:i,pixelFormat:$n.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===pr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:ts.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:gt.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:ae(this,Bn,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,ae(this,Gn,"f")&&(ae(this,Wn,"f")&&clearTimeout(ae(this,Wn,"f")),he(this,Wn,setTimeout((()=>{this.disposed||ae(this,xn,"m",qn).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){he(this,jn,t,"f")}getPixelFormat(){return ae(this,jn,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(ae(this,xn,"m",zn).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=Xe.convert(ae(this,Un,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=ae(this,kn,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=ae(this,xn,"m",Jn).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=ae(this,xn,"m",Jn).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),ae(this,On,"f").dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function rs(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function ns(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}An=is,On=new WeakMap,Dn=new WeakMap,Ln=new WeakMap,Mn=new WeakMap,Fn=new WeakMap,Pn=new WeakMap,kn=new WeakMap,Bn=new WeakMap,Nn=new WeakMap,Un=new WeakMap,jn=new WeakMap,Gn=new WeakMap,Wn=new WeakMap,Vn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,xn=new WeakSet,zn=function(){return"disabled"!==this.singleFrameMode},Zn=function(){return!this.videoSrc&&"opened"===ae(this,On,"f").state},Kn=function(){for(let t in ae(this,Vn,"f"))if(1==ae(this,Vn,"f")[t])return!0;return!1},qn=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!ae(this,Gn,"f"))return ae(this,Wn,"f")&&clearTimeout(ae(this,Wn,"f")),void he(this,Wn,setTimeout((()=>{this.disposed||ae(this,xn,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;is._onLog&&is._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=ae(this,Nn,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=ae(this,Nn,"f"))||void 0===t||t.onErrorReceived(ut.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),is._onLog&&is._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),ae(this,Mn,"f").fire("frameAddedToBuffer",null,{async:!0})):is._onLog&&is._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:e()}else e();ae(this,Wn,"f")&&clearTimeout(ae(this,Wn,"f")),he(this,Wn,setTimeout((()=>{this.disposed||ae(this,xn,"m",t).call(this)}),this.fetchInterval),"f")},Jn=function(t){if(!ae(this,Dn,"f"))throw new Error("Camera view is not set.");if(ae(this,Dn,"f").disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ae(this,xn,"m",zn).call(this)&&!ae(this,On,"f").isVideoLoaded())throw new Error("Video is not loaded.");if(ae(this,xn,"m",zn).call(this)&&!ae(this,Dn,"f")._cvsSingleFrameMode)throw new Error("No image is selected.");const e=ae(this,Dn,"f")._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=ae(this,Dn,"f")._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(ae(this,xn,"m",zn).call(this)){const t=ae(this,Dn,"f")._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=ae(this,Dn,"f").getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return ss.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return ss.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return ss.multiply(t,[e,0,0,0,i,0,0,0,1])}}var os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Es,Cs,Ts,bs,Ss,Is,xs,As;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(os||(os={}));class Rs{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(ns(Rs,as,!1,"f",hs),!1):(ns(Rs,as,!0,"f",hs),!0)}get disposed(){return rs(this,gs,"f")}constructor(){ls.set(this,os.RGBA),cs.set(this,null),us.set(this,null),ds.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,fs.set(this,null),gs.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==rs(Rs,as,"f",hs)&&Rs.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!rs(Rs,as,"f",hs))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Rs._onLog&&(o=Date.now(),Rs._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=os.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!rs(Rs,as,"f",hs)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Rs._onLog&&Rs._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);ns(this,us,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),ns(this,ds,e(t),"f"),ns(this,cs,i(t),"f"),ns(this,ls,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[os.GREY,os.GREY32].includes(p)?1:0);let m,_,v=ss.translate(ss.identity(),-1,-1);v=ss.scale(v,2,2),v=ss.scale(v,1/t.canvas.width,1/t.canvas.height),m=ss.translate(v,u,d),m=ss.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=ss.translate(ss.identity(),a/i,h/r),_=ss.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,rs(this,cs,"f"),e),v(t,rs(this,us,"f"),rs(this,ds,"f"),rs(this,cs,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Rs._onLog&&Rs._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Rs._onLog&&Rs._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===os.GREY?os.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Rs._onLog&&Rs._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Rs._onLog&&(n=Date.now(),Rs._onLog("transformPixelFormat(), START: "+n)),e===i)return Rs._onLog&&Rs._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[os.RGBA,os.RBGA,os.GRBA,os.GBRA,os.BRGA,os.BGRA];if(o.includes(e))if(i===os.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Rs._onLog&&(s=Date.now(),Rs._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=os.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),rs(Rs,as,"f",hs)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Rs._onLog&&Rs._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===os.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(ae(this,ys,"f")||he(this,ys,new Os,"f"),!ae(this,ys,"f").magnifierCanvas)return;document.body.contains(ae(this,ys,"f").magnifierCanvas)||(ae(this,ys,"f").magnifierCanvas.style.position="fixed",ae(this,ys,"f").magnifierCanvas.style.boxSizing="content-box",ae(this,ys,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(ae(this,ys,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void ae(this,Es,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];ae(this,ys,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(ae(this,ys,"f").magnifierCanvas.style.left="auto",ae(this,ys,"f").magnifierCanvas.style.top="0",ae(this,ys,"f").magnifierCanvas.style.right="0"):(ae(this,ys,"f").magnifierCanvas.style.left="0",ae(this,ys,"f").magnifierCanvas.style.top="0",ae(this,ys,"f").magnifierCanvas.style.right="auto")}ae(this,ys,"f").show()})),Es.set(this,(()=>{ae(this,ys,"f")&&ae(this,ys,"f").hide()})),Cs.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if(e="string"==typeof t?await $e(t):t,e instanceof HTMLDivElement&&0==e.childElementCount){const t=ae(this,_s,"m",Ts).call(this);this._setUIElement(t),e.append(this.getUIElement()),this.UIElement=e}else this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new ir,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(Ne(t)){he(this,vs,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let o;if(n===s.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{ae(this,bs,"f",As).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,ae(this,bs,"f",As).delete(t),ae(this,bs,"f",xs).add(t)}))}else ae(this,bs,"f",Is)||(he(this,bs,!0,"f",Is),console.warn("The requested audio tracks exceed 64 and will not be played."));t&&ae(this,bs,"f",As).add(t)}static vibrate(){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ls.vibrateDuration)}}bs=Ls,Ss={value:"data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"},Is={value:!1},xs={value:new Set},As={value:new Set},Ls.beepSoundSource=ae(Ls,bs,"f",Ss),Ls.vibrateDuration=300;var Ms=Object.freeze({__proto__:null,CameraEnhancer:is,CameraEnhancerModule:class{static getVersion(){return"4.0.2"}},CameraView:nr,DrawingStyleManager:Ji,get EnumDrawingItemMediaType(){return Ce},get EnumDrawingItemState(){return Te},get EnumEnhancedFeatures(){return be},Feedback:Ls,ImageDrawingItem:class extends Pe{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return ae(this,ri,"f")}constructor(t,e,i,r){if(super(null,r),ii.set(this,void 0),ri.set(this,void 0),!Ye(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new Ie.Image(t,{left:e.x,top:e.y}));else{if(!Ne(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;if(i.width=t.width,i.height=t.height,t.format===s.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new Ie.Control({positionHandler:oi,actionHandler:li(i>0?i-1:r,hi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=Ie.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){ae(this,fi,"f")&&this.setLine(ae(this,fi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!je(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else he(this,fi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return ae(this,fi,"f")?JSON.parse(JSON.stringify(ae(this,fi,"f"))):null}},QuadDrawingItem:Ki,RectDrawingItem:si,TextDrawingItem:di});const Fs="undefined"==typeof self,Ps=(()=>{if(!Fs&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),ks=t=>{if(null==t&&(t="./"),Fs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};null==nt.dbr&&(nt.dbr=Ps),ot.dbr={js:!1,wasm:!0,deps:["license","dip"]},rt.dbr={};const Bs="1.2.0";"string"!=typeof nt.std&&w(nt.std.version,Bs)<0&&(nt.std={version:Bs,path:ks(Ps+`../../dynamsoft-capture-vision-std@${Bs}/dist/`)});const Ns="2.2.10";(!nt.dip||"string"!=typeof nt.dip&&w(nt.dip.version,Ns)<0)&&(nt.dip={version:Ns,path:ks(Ps+`../../dynamsoft-image-processing@${Ns}/dist/`)});const Us="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};var js,Gs,Ws,Vs;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(js||(js={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Gs||(Gs={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(Ws||(Ws={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(Vs||(Vs={}));var Ys=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=it.dbr&&it.dbr.wasm,e=it.dbr&&it.dbr.worker;return`10.2.10(Worker: ${e||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:Us,get EnumExtendedBarcodeResultType(){return js},get EnumQRCodeErrorCorrectionLevel(){return Gs},get EnumLocalizationMode(){return Ws},get EnumDeblurMode(){return Vs}}); -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Utility JS Edition - * @website https://www.dynamsoft.com - * @copyright Copyright 2024, Dynamsoft Corporation - * @author Dynamsoft - * @version 1.2.10 - * @fileoverview Dynamsoft JavaScript Library for Core - * More info DU JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/utility-module.html - */const Hs=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await zs(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),Xs=t=>{const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},zs=async(t,e)=>{const i=Xs(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},Zs=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===s.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===s.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;rObject.values(Ks).includes(t)||Ks.hasOwnProperty(t),Js=(t,e)=>"string"==typeof t?e[Ks[t]]:e[t],Qs=(t,e,i)=>{"string"==typeof t?e[Ks[t]]=i:e[t]=i};var $s=Object.freeze({__proto__:null,ImageManager:class{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const r=Zs(t);return Hs(r,e,i)}},MultiFrameResultCrossFilter:class{constructor(){this.verificationEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!0,[lt.CRIT_DETECTED_QUAD]:!0,[lt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!1,[lt.CRIT_DETECTED_QUAD]:!1,[lt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[lt.CRIT_BARCODE]:3e3,[lt.CRIT_TEXT_LINE]:3e3,[lt.CRIT_DETECTED_QUAD]:3e3,[lt.CRIT_NORMALIZED_IMAGE]:3e3}}enableResultCrossVerification(t,e){qs(t)&&Qs(t,this.verificationEnabled,e)}isResultCrossVerificationEnabled(t){return!!qs(t)&&Js(t,this.verificationEnabled)}enableResultDeduplication(t,e){qs(t)&&Qs(t,this.duplicateFilterEnabled,e)}isResultDeduplicationEnabled(t){return!!qs(t)&&Js(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){qs(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Qs(t,this.duplicateForgetTime,e))}getDuplicateForgetTime(t){return qs(t)?Js(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[lt.CRIT_BARCODE,lt.CRIT_TEXT_LINE,lt.CRIT_DETECTED_QUAD];for(let i=0;i{const i=Xs(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r}});let to="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}to=t.substring(0,t.lastIndexOf("/")+1)}const eo=t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t};ht.engineResourcePaths={std:eo(to+"../../dynamsoft-capture-vision-std@1.2.0/dist/"),dip:eo(to+"../../dynamsoft-image-processing@2.2.10/dist/"),core:eo(to+"../../dynamsoft-core@3.2.10/dist/"),license:eo(to+"../../dynamsoft-license@3.2.10/dist/"),cvr:eo(to+"../../dynamsoft-capture-vision-router@2.2.10/dist/"),dce:eo(to+"../../dynamsoft-camera-enhancer@4.0.2/dist/")},t.CVR=ne,t.Core=wt,t.DBR=Ys,t.DCE=Ms,t.License=Wt,t.Utility=$s,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft={})}(this,(function(t){"use strict";function e(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function i(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var r,n,s;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(r||(r={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(n||(n={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(s||(s={}));const o=t=>Object.prototype.toString.call(t),a=t=>Array.isArray?Array.isArray(t):"[object Array]"===o(t),h=t=>"[object Boolean]"===o(t),l=t=>"number"==typeof t&&!Number.isNaN(t),c=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),u=t=>!(!c(t)||!(t.bytes instanceof Uint8Array)||!l(t.width)||t.width<=0||!l(t.height)||t.height<=0||!l(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!f(t.tag)),d=t=>!(!c(t)||!l(t.left)||t.left<0||!l(t.top)||t.top<0||!l(t.right)||t.right<0||!l(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!h(t.isMeasuredInPercentage)),f=t=>!!c(t)&&!!l(t.imageId)&&"type"in t,g=t=>!(!c(t)||!m(t.startPoint)||!m(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),m=t=>!!c(t)&&!!l(t.x)&&!!l(t.y),p=t=>!!c(t)&&!!a(t.points)&&0!=t.points.length&&!t.points.some((t=>!m(t))),_=t=>!!c(t)&&!!a(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!m(t))),v=t=>!(!c(t)||!l(t.x)||!l(t.y)||!l(t.width)||t.width<0||!l(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!h(t.isMeasuredInPercentage));async function y(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(t+" "+n.status):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}const w=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t=e(this,b,"f"))switch(e(this,S,"f")){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:if(e(this,T,"f").push(t),c(e(this,x,"f"))&&l(e(this,x,"f").imageId)&&1==e(this,x,"f").keepInBuffer)for(;e(this,T,"f").length>e(this,b,"f");){const t=e(this,T,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)!==e(this,x,"f").imageId}));e(this,T,"f").splice(t,1)}else e(this,T,"f").splice(0,e(this,T,"f").length-e(this,b,"f"))}else e(this,T,"f").push(t)}getImage(){if(0===e(this,T,"f").length)return null;let i;if(e(this,x,"f")&&l(e(this,x,"f").imageId)){const t=e(this,C,"m",R).call(this,e(this,x,"f").imageId);if(t<0)throw new Error(`Image with id ${e(this,x,"f").imageId} doesn't exist.`);i=e(this,T,"f").slice(t,t+1)[0]}else i=e(this,T,"f").pop();if([s.IPF_RGB_565,s.IPF_RGB_555,s.IPF_RGB_888,s.IPF_ARGB_8888,s.IPF_RGB_161616,s.IPF_ARGB_16161616,s.IPF_ABGR_8888,s.IPF_ABGR_16161616,s.IPF_BGR_888].includes(i.format)){if(e(this,A,"f")===n.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const e=new Uint8Array(i.width*i.height);for(let t=0;t0!==t.length&&t.every((t=>l(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!h(e))throw new TypeError("Invalid 'keepInBuffer'.");i(this,x,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){i(this,x,null,"f")}hasImage(t){return e(this,C,"m",R).call(this,t)>=0}startFetching(){i(this,I,!0,"f")}stopFetching(){i(this,I,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(i(this,b,t,"f");e(this,T,"f")&&e(this,T,"f").length>t;)e(this,T,"f").shift()}getMaxImageCount(){return e(this,b,"f")}getImageCount(){return e(this,T,"f").length}clearBuffer(){e(this,T,"f").length=0}isBufferEmpty(){return 0===e(this,T,"f").length}setBufferOverflowProtectionMode(t){i(this,S,t,"f")}getBufferOverflowProtectionMode(){return e(this,S,"f")}setColourChannelUsageType(t){i(this,A,t,"f")}getColourChannelUsageType(){return e(this,A,"f")}};T=new WeakMap,b=new WeakMap,S=new WeakMap,I=new WeakMap,x=new WeakMap,A=new WeakMap,C=new WeakSet,R=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return e(this,T,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))};const D="undefined"==typeof self,L=(()=>{if(!D&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),M=t=>{if(null==t&&(t="./"),D);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};let F,P,k,B,N;"undefined"!=typeof navigator&&(F=navigator,P=F.userAgent,k=F.platform,B=F.mediaDevices),function(){if(!D){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:F.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:k,search:"Win"},Mac:{str:k},Linux:{str:k}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||P,o=n.search||e,a=n.verStr||P,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||P,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=P.indexOf("Windows NT")&&(n="HarmonyOS"),N={browser:i,version:r,OS:n}}D&&(N={browser:"ssr",version:0,OS:"ssr"})}();const U="undefined"!=typeof WebAssembly&&P&&!(/Safari/.test(P)&&!/Chrome/.test(P)&&/\(.+\s11_2_([2-6]).*\)/.test(P)),j=!("undefined"==typeof Worker),G=!(!B||!B.getUserMedia),V=async()=>{let t=!1;if(G)try{(await B.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===N.browser&&N.version>66||"Safari"===N.browser&&N.version>13||"OPR"===N.browser&&N.version>43||"Edge"===N.browser&&N.version;const W=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Y=class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(W(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,W(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}};const H={},X=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(H[t]=H[t]||new Y);await Promise.all(i)},z=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=H[t]=H[t]||new Y(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let Z,K=0;const q=()=>K++,J={};let Q;const $=t=>{Q=t,Z&&Z.postMessage({type:"setBLog",body:{value:!!t}})};let tt=!1;const et=t=>{tt=t,Z&&Z.postMessage({type:"setBDebug",body:{value:!!t}})},it={},rt={},nt={std:{version:"1.2.10",path:M(L+"../../dynamsoft-capture-vision-std@1.2.10/dist/")},core:{version:"3.2.30",path:L}},st=new Proxy(nt,{get(t,e,i){let r=Reflect.get(t,e,i);return r&&r.path&&(r=r.path),r}}),ot={dip:{wasm:!0}},at=async t=>{let e;t instanceof Array||(t=t?[t]:[]);{let t=H.core;e=!t||t.isEmpty}let i=new Map;for(let e of t){if(e=e.toLowerCase(),"std"==e||"core"==e)continue;if(!ot[e])throw Error("The '"+e+"' module cannot be found.");let t=ot[e].deps;if(null==t?void 0:t.length)for(let e of t){let t=H[e];i.has(e)||i.set(e,!t||t.isEmpty)}let r=H[e];i.has(e)||i.set(e,!r||r.isEmpty)}let r=[];e&&r.push("core"),r.push(...i.keys()),await z(r,(async()=>{const t=[...i.entries()].filter((t=>t[1])).map((t=>t[0])),r={};for(let t in st){if("rootDirectory"==t)continue;let e=st[t];st.rootDirectory&&(e.startsWith("http://")||e.startsWith("https://")||(e=st.rootDirectory+"/"+e)),r[t]=M(e)}const n={};for(let e of t)n[e]=ot[e];const s={engineResourcePaths:r,autoResources:n,names:t};let o=new Y;if(e){s.needLoadCore=!0;let t=r.core+ht._workerName;r.rootDirectory&&(t=r.rootDirectory+t),t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),Z=new Worker(t),Z.onerror=t=>{let e=new Error(t.message);o.reject(e)},Z.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":Q&&Q(e.message);break;case"task":try{J[r](n),delete J[r]}catch(t){throw delete J[r],t}break;case"event":try{J[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!Q,s.bd=tt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await X("worker");let a=K++;J[a]=t=>{if(t.success)Object.assign(it,t.versions),"{}"!==JSON.stringify(t.versions)&&(ht._versions=t.versions),o.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),o.reject(e)}},Z.postMessage({type:"loadWasm",body:s,id:a}),e&&z("worker",(()=>Promise.resolve())),await o}))};class ht{static get engineResourcePaths(){return st}static set engineResourcePaths(t){Object.assign(nt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return Q}static set _onLog(t){$(t)}static get _bDebug(){return tt}static set _bDebug(t){et(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!H[t]&&H[t].isFulfilled}static async loadWasm(t){return await at(t)}static async detectEnvironment(){return await(async()=>({wasm:U,worker:j,getUserMedia:G,camera:await V(),browser:N.browser,version:N.version,OS:N.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.2.30(Worker: ${it.core&&it.core.worker||"Not Loaded"}, Wasm: ${it.core&&it.core.wasm||"Not Loaded"})`}static enableLogging(){O._onLog=console.log,ht._onLog=console.log}static disableLogging(){O._onLog=null,ht._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var lt,ct,ut,dt,ft,gt,mt,pt,_t,vt,yt;ht._bSupportDce4Module=-1,ht._bSupportIRTModule=-1,ht._versions=null,ht._workerName="core.worker.js",ht.browserInfo=N,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(lt||(lt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(ct||(ct={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID"}(ut||(ut={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(dt||(dt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(ft||(ft={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(gt||(gt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(mt||(mt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(pt||(pt={})),function(t){t[t.IRUT_NULL=0]="IRUT_NULL",t[t.IRUT_COLOUR_IMAGE=1]="IRUT_COLOUR_IMAGE",t[t.IRUT_SCALED_DOWN_COLOUR_IMAGE=2]="IRUT_SCALED_DOWN_COLOUR_IMAGE",t[t.IRUT_GRAYSCALE_IMAGE=4]="IRUT_GRAYSCALE_IMAGE",t[t.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE=8]="IRUT_TRANSOFORMED_GRAYSCALE_IMAGE",t[t.IRUT_ENHANCED_GRAYSCALE_IMAGE=16]="IRUT_ENHANCED_GRAYSCALE_IMAGE",t[t.IRUT_PREDETECTED_REGIONS=32]="IRUT_PREDETECTED_REGIONS",t[t.IRUT_BINARY_IMAGE=64]="IRUT_BINARY_IMAGE",t[t.IRUT_TEXTURE_DETECTION_RESULT=128]="IRUT_TEXTURE_DETECTION_RESULT",t[t.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE=256]="IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE",t[t.IRUT_TEXTURE_REMOVED_BINARY_IMAGE=512]="IRUT_TEXTURE_REMOVED_BINARY_IMAGE",t[t.IRUT_CONTOURS=1024]="IRUT_CONTOURS",t[t.IRUT_LINE_SEGMENTS=2048]="IRUT_LINE_SEGMENTS",t[t.IRUT_TEXT_ZONES=4096]="IRUT_TEXT_ZONES",t[t.IRUT_TEXT_REMOVED_BINARY_IMAGE=8192]="IRUT_TEXT_REMOVED_BINARY_IMAGE",t[t.IRUT_CANDIDATE_BARCODE_ZONES=16384]="IRUT_CANDIDATE_BARCODE_ZONES",t[t.IRUT_LOCALIZED_BARCODES=32768]="IRUT_LOCALIZED_BARCODES",t[t.IRUT_SCALED_UP_BARCODE_IMAGE=65536]="IRUT_SCALED_UP_BARCODE_IMAGE",t[t.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE=131072]="IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE",t[t.IRUT_COMPLEMENTED_BARCODE_IMAGE=262144]="IRUT_COMPLEMENTED_BARCODE_IMAGE",t[t.IRUT_DECODED_BARCODES=524288]="IRUT_DECODED_BARCODES",t[t.IRUT_LONG_LINES=1048576]="IRUT_LONG_LINES",t[t.IRUT_CORNERS=2097152]="IRUT_CORNERS",t[t.IRUT_CANDIDATE_QUAD_EDGES=4194304]="IRUT_CANDIDATE_QUAD_EDGES",t[t.IRUT_DETECTED_QUADS=8388608]="IRUT_DETECTED_QUADS",t[t.IRUT_LOCALIZED_TEXT_LINES=16777216]="IRUT_LOCALIZED_TEXT_LINES",t[t.IRUT_RECOGNIZED_TEXT_LINES=33554432]="IRUT_RECOGNIZED_TEXT_LINES",t[t.IRUT_NORMALIZED_IMAGES=67108864]="IRUT_NORMALIZED_IMAGES",t[t.IRUT_SHORT_LINES=134217728]="IRUT_SHORT_LINES",t[t.IRUT_ALL=268435455]="IRUT_ALL"}(_t||(_t={})),function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(vt||(vt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(yt||(yt={}));var wt=Object.freeze({__proto__:null,CoreModule:ht,get EnumBufferOverflowProtectionMode(){return r},get EnumCapturedResultItemType(){return lt},get EnumColourChannelUsageType(){return n},get EnumCornerType(){return ct},get EnumErrorCode(){return ut},get EnumGrayscaleEnhancementMode(){return dt},get EnumGrayscaleTransformationMode(){return ft},get EnumImagePixelFormat(){return s},get EnumImageTagType(){return gt},get EnumIntermediateResultUnitType(){return _t},get EnumPDFReadingMode(){return mt},get EnumRasterDataSource(){return pt},get EnumRegionObjectElementType(){return vt},get EnumSectionType(){return yt},ImageSourceAdapter:O,_isArc:t=>!(!c(t)||!l(t.x)||!l(t.y)||!l(t.radius)||t.radius<0||!l(t.startAngle)||!l(t.endAngle)),_isContour:t=>!!c(t)&&!!a(t.points)&&0!=t.points.length&&!t.points.some((t=>!m(t))),_isDSImageData:u,_isDSRect:d,_isImageTag:f,_isLineSegment:g,_isPoint:m,_isPolygon:p,_isQuad:_,_isRect:v,get bDebug(){return tt},bSupportBigInt:E,checkIsLink:function(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)},compareVersion:w,doOrWaitAsyncDependency:z,engineResourcePaths:nt,getNextTaskID:q,innerVersions:it,loadWasm:at,mapAsyncDependency:H,mapPackageRegister:rt,mapTaskCallBack:J,newAsyncDependency:t=>{let e=H[t],i=!1;return e?e.isEmpty?e.task=()=>{}:i=!0:e=H[t]=new Y((()=>{})),{p:e,justWait:i}},get onLog(){return Q},requestResource:y,setBDebug:et,setOnLog:$,waitAsyncDependency:X,get worker(){return Z},workerAutoResources:ot});let Et="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}Et=t.substring(0,t.lastIndexOf("/")+1)}const Ct=t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t};ht.engineResourcePaths={std:Ct(Et+"../../dynamsoft-capture-vision-std@1.2.10/dist/"),dip:Ct(Et+"../../dynamsoft-image-processing@2.2.30/dist/"),core:Ct(Et+"../../dynamsoft-core@3.2.30/dist/"),license:Ct(Et+"../../dynamsoft-license@3.2.21/dist/"),cvr:Ct(Et+"../../dynamsoft-capture-vision-router@2.2.30/dist/"),dce:Ct(Et+"../../dynamsoft-camera-enhancer@4.0.3/dist/"),dbr:Ct(Et+"../../dynamsoft-barcode-reader@10.2.10/dist/")};const Tt="undefined"==typeof self,bt=Tt?{}:self,St=(()=>{if(!Tt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),It=t=>{if(null==t&&(t="./"),Tt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},xt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let At=class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(xt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,xt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}};const Rt=" is not allowed to change after `createInstance` or `loadWasm` is called.",Ot=!Tt&&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"))||"",Dt=(t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`license`"+Rt);i._license=e};!Tt&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Lt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{const i=t;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Rt);i._licenseServer=Lt(e)},Ft=(t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Rt);i._deviceFriendlyName=e||""};let Pt,kt,Bt,Nt,Ut;"undefined"!=typeof navigator&&(Pt=navigator,kt=Pt.userAgent,Bt=Pt.platform,Nt=Pt.mediaDevices),function(){if(!Tt){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Pt.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Bt,search:"Win"},Mac:{str:Bt},Linux:{str:Bt}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||kt,o=n.search||e,a=n.verStr||kt,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||kt,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=kt.indexOf("Windows NT")&&(n="HarmonyOS"),Ut={browser:i,version:r,OS:n}}Tt&&(Ut={browser:"ssr",version:0,OS:"ssr"})}(),Nt&&Nt.getUserMedia,"Chrome"===Ut.browser&&Ut.version>66||"Safari"===Ut.browser&&Ut.version>13||"OPR"===Ut.browser&&Ut.version>43||"Edge"===Ut.browser&&Ut.version;const jt=async()=>(at("license"),z("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Lt(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(bt.crypto||(s="Please upgrade your browser to support online key."),bt.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Rt)})(Vt),o=new At;Vt._pLoad.task=o,(async()=>{try{await Vt._pLoad}catch(t){}})();let a=q();J[a]=e=>{if(e.message&&Vt._onAuthMessage){let t=Vt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(Q&&Q("init license success"),e.message&&console.warn(e.message),ht._bSupportIRTModule=e.bSupportIRTModule,ht._bSupportDce4Module=e.bSupportDce4Module,Vt.bPassValidation=!0):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){let t=nt.license;nt.rootDirectory&&(t=nt.rootDirectory+"/"+t),t=It(t),(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.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 t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Vt._bNeverShowDialog,engineResourcePath:t,_onLog:Q},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await X("worker"),Z.postMessage({type:"dynamsoft",body:{v:"3.2.21",brtk:!!t,bptk:1===t,l:e,os:Ut,fn:Vt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),Vt.bCallInitLicense=!0,await o})));let Gt;rt.license={},rt.license.dynamsoft=jt,rt.license.getAR=async()=>{{let t=H.dynamsoft_inited;t&&t.isRejected&&await t}return Z?new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success){delete i.success;{let t=Vt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},Z.postMessage({type:"getAR",id:i})})):null};let Vt=class t{static setLicenseServer(e){Mt(t,e)}static get license(){return this._license}static set license(e){Dt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Mt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Ft(t,e)}static initLicense(e,i){if(Dt(t,e),t.bCallInitLicense=!0,i)return jt()}static setDeviceFriendlyName(e){Ft(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await z("dynamsoft_uuid",(async()=>{await at();let t=new At,e=q();J[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Z.postMessage({type:"getDeviceUUID",id:e}),Gt=await t})),Gt))()}};Vt._pLoad=new At,Vt.bPassValidation=!1,Vt.bCallInitLicense=!1,Vt._license=Ot,Vt._licenseServer=[],Vt._deviceFriendlyName="",null==nt.license&&(nt.license=St),ot.license={wasm:!0},rt.license.LicenseManager=Vt;const Wt="1.2.10";"string"!=typeof nt.std&&w(nt.std.version,Wt)<0&&(nt.std={version:Wt,path:It(St+`../../dynamsoft-capture-vision-std@${Wt}/dist/`)});var Yt=Object.freeze({__proto__:null,LicenseManager:Vt,LicenseModule:class{static getVersion(){return`3.2.21(Worker: ${it.license&&it.license.worker||"Not Loaded"}, Wasm: ${it.license&&it.license.wasm||"Not Loaded"})`}}});const Ht=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Xt=class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Ht(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Ht(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}};class zt{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var Zt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const Kt=(t,e)=>{for(let t in e._irrRegistryState)e._irrRegistryState[t]=!1;for(let i of t._intermediateResultReceiverSet)if(i.isDce)e._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let t in i)e._irrRegistryState[t]||(e._irrRegistryState[t]=!!i[t])};let qt=class{constructor(t){this._irrRegistryState=Zt,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._cvr._intermediateResultReceiverSet.add(t),Kt(this._cvr,this);let e=-1,i={};if(!t.isDce){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=q();J[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},Z.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:String(e),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._cvr._intermediateResultReceiverSet.delete(t),Kt(this._cvr,this),await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}};const Jt="undefined"==typeof self,Qt=(()=>{if(!Jt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),$t=t=>{if(null==t&&(t="./"),Jt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var te;null==nt.cvr&&(nt.cvr=Qt),ot.cvr={js:!0,wasm:!0,deps:["license","dip"]},rt.cvr={};const ee="1.2.10";"string"!=typeof nt.std&&w(nt.std.version,ee)<0&&(nt.std={version:ee,path:$t(Qt+`../../dynamsoft-capture-vision-std@${ee}/dist/`)});const ie="2.2.30";(!nt.dip||"string"!=typeof nt.dip&&w(nt.dip.version,ie)<0)&&(nt.dip={version:ie,path:$t(Qt+`../../dynamsoft-image-processing@${ie}/dist/`)});let re=class{static getVersion(){return this._version}};var ne,se;function oe(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;oe(t.referencedItem,e)}}re._version=`2.2.30(Worker: ${null===(te=it.cvr)||void 0===te?void 0:te.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ne||(ne={})),function(t){t[t.IRUT_NULL=0]="IRUT_NULL",t[t.IRUT_COLOUR_IMAGE=1]="IRUT_COLOUR_IMAGE",t[t.IRUT_SCALED_DOWN_COLOUR_IMAGE=2]="IRUT_SCALED_DOWN_COLOUR_IMAGE",t[t.IRUT_GRAYSCALE_IMAGE=4]="IRUT_GRAYSCALE_IMAGE",t[t.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE=8]="IRUT_TRANSOFORMED_GRAYSCALE_IMAGE",t[t.IRUT_ENHANCED_GRAYSCALE_IMAGE=16]="IRUT_ENHANCED_GRAYSCALE_IMAGE",t[t.IRUT_PREDETECTED_REGIONS=32]="IRUT_PREDETECTED_REGIONS",t[t.IRUT_BINARY_IMAGE=64]="IRUT_BINARY_IMAGE",t[t.IRUT_TEXTURE_DETECTION_RESULT=128]="IRUT_TEXTURE_DETECTION_RESULT",t[t.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE=256]="IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE",t[t.IRUT_TEXTURE_REMOVED_BINARY_IMAGE=512]="IRUT_TEXTURE_REMOVED_BINARY_IMAGE",t[t.IRUT_CONTOURS=1024]="IRUT_CONTOURS",t[t.IRUT_LINE_SEGMENTS=2048]="IRUT_LINE_SEGMENTS",t[t.IRUT_TEXT_ZONES=4096]="IRUT_TEXT_ZONES",t[t.IRUT_TEXT_REMOVED_BINARY_IMAGE=8192]="IRUT_TEXT_REMOVED_BINARY_IMAGE",t[t.IRUT_CANDIDATE_BARCODE_ZONES=16384]="IRUT_CANDIDATE_BARCODE_ZONES",t[t.IRUT_LOCALIZED_BARCODES=32768]="IRUT_LOCALIZED_BARCODES",t[t.IRUT_SCALED_UP_BARCODE_IMAGE=65536]="IRUT_SCALED_UP_BARCODE_IMAGE",t[t.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE=131072]="IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE",t[t.IRUT_COMPLEMENTED_BARCODE_IMAGE=262144]="IRUT_COMPLEMENTED_BARCODE_IMAGE",t[t.IRUT_DECODED_BARCODES=524288]="IRUT_DECODED_BARCODES",t[t.IRUT_LONG_LINES=1048576]="IRUT_LONG_LINES",t[t.IRUT_CORNERS=2097152]="IRUT_CORNERS",t[t.IRUT_CANDIDATE_QUAD_EDGES=4194304]="IRUT_CANDIDATE_QUAD_EDGES",t[t.IRUT_DETECTED_QUADS=8388608]="IRUT_DETECTED_QUADS",t[t.IRUT_LOCALIZED_TEXT_LINES=16777216]="IRUT_LOCALIZED_TEXT_LINES",t[t.IRUT_RECOGNIZED_TEXT_LINES=33554432]="IRUT_RECOGNIZED_TEXT_LINES",t[t.IRUT_NORMALIZED_IMAGES=67108864]="IRUT_NORMALIZED_IMAGES",t[t.IRUT_SHORT_LINES=134217728]="IRUT_SHORT_LINES",t[t.IRUT_ALL=134217727]="IRUT_ALL"}(se||(se={}));var ae=Object.freeze({__proto__:null,CaptureVisionRouter:class t{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(ht.browserInfo.OS)?2048:4096,this._isa=null,this._dsImage=null,this._instanceID=void 0,this._bPauseScan=!0,this._bNeedOutputOriginalImage=!1,this._canvas=null,this._resultReceiverSet=new Set,this._isaStateListenerSet=new Set,this._resultFilterSet=new Set,this._intermediateResultReceiverSet=new Set,this._intermediateResultManager=null,this._bufferdItemsManager=null,this._bOpenDetectVerify=!1,this._bOpenNormalizeVerify=!1,this._bOpenBarcodeVerify=!1,this._bOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._compressRate=0,this._dynamsoft=!1,this.captureInParallel=!0,this.bDestroyed=!1,this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this),this._promiseStartScan=null}get disposed(){return this.bDestroyed}static async createInstance(){if(!rt.license)throw Error("Module `license` is not existed.");await rt.license.dynamsoft(),await at(["cvr"]);const e=new t,i=new Xt;let r=q();return J[r]=async t=>{var r;if(t.success)e._instanceID=t.instanceID,e._currentSettings=JSON.parse(t.outputSettings),re._version=`2.2.30(Worker: ${null===(r=it.cvr)||void 0===r?void 0:r.worker}, Wasm: ${t.version})`,0===ht.bSupportDce4Module&&(e._intermediateResultManager=e.getIntermediateResultManager(!0)),i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},Z.postMessage({type:"cvr_createInstance",id:r}),i}async _singleFrameModeCallback(t){this._isa.getCameraView().setScanLaserVisible(!0);for(let e of this._resultReceiverSet)this._bNeedOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of this._resultReceiverSet)t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of this._resultReceiverSet)if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._bNeedOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(this._checkIsDisposed(),t){if(this._isa=t,t.isCameraEnhancer){this._intermediateResultManager&&(this._isa._intermediateResultReceiver.isDce=!0,this._intermediateResultManager.addResultReceiver(this._isa._intermediateResultReceiver));const t=this._isa.getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,this._resultReceiverSet.add(e)}}}else this._isa=null}getInput(){return this._isa}addImageSourceStateListener(t){if(this._checkIsDisposed(),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&this._isaStateListenerSet.add(t)}removeImageSourceStateListener(t){return this._checkIsDisposed(),this._isaStateListenerSet.delete(t)}addResultReceiver(t){if(this._checkIsDisposed(),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(this._resultReceiverSet.add(t),this._setCrrRegistry())}removeResultReceiver(t){this._checkIsDisposed(),this._resultReceiverSet.delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of this._resultReceiverSet)e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Xt;let i=q();return J[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},Z.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(this._checkIsDisposed(),"object"!=typeof t)return console.warn("Invalid filter.");if(t&&Object.keys(t)){this._resultFilterSet.add(t),this._handleFilterSwitch();for(let t of this._resultFilterSet)await this._enableResultCrossVerification(t.verificationEnabled),await this._enableResultDeduplication(t.duplicateFilterEnabled),await this._setDuplicateForgetTime(t.duplicateForgetTime)}}async removeResultFilter(t){this._checkIsDisposed(),this._resultFilterSet.delete(t),this._handleFilterSwitch();for(let t of this._resultFilterSet)await this._enableResultCrossVerification(t.verificationEnabled),await this._enableResultDeduplication(t.duplicateFilterEnabled),await this._setDuplicateForgetTime(t.duplicateForgetTime)}_handleFilterSwitch(){this._bOpenBarcodeVerify=!1,this._bOpenLabelVerify=!1,this._bOpenDetectVerify=!1,this._bOpenNormalizeVerify=!1;for(let t of this._resultFilterSet)t.isResultCrossVerificationEnabled(lt.CRIT_BARCODE)&&(this._bOpenBarcodeVerify=!0),t.isResultCrossVerificationEnabled(lt.CRIT_TEXT_LINE)&&(this._bOpenLabelVerify=!0),t.isResultCrossVerificationEnabled(lt.CRIT_DETECTED_QUAD)&&(this._bOpenDetectVerify=!0),t.isResultCrossVerificationEnabled(lt.CRIT_NORMALIZED_IMAGE)&&(this._bOpenNormalizeVerify=!0)}async startCapturing(t){var e,i;if(this._checkIsDisposed(),!this._bPauseScan)return;if(!this._isa)throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const r=await this.containsTask(t);return await at(r),r.includes("dlr")&&!(null===(e=rt.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)&&await(null===(i=rt.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",nt.dlr)),this._isa.isCameraEnhancer&&(r.includes("ddn")?this._isa.setPixelFormat(s.IPF_ABGR_8888):this._isa.setPixelFormat(s.IPF_GRAYSCALED)),void 0!==this._isa.singleFrameMode&&"disabled"!==this._isa.singleFrameMode?(this._templateName=t,void this._isa.on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(this._isa.getColourChannelUsageType()===n.CCUT_AUTO&&this._isa.setColourChannelUsageType(r.includes("ddn")?n.CCUT_FULL_CHANNEL:n.CCUT_Y_CHANNEL_ONLY),this._promiseStartScan&&this._promiseStartScan.isPending?this._promiseStartScan:(this._promiseStartScan=new Xt(((e,i)=>{if(this.disposed)return;let r=q();J[r]=async r=>{if(this._promiseStartScan&&!this._promiseStartScan.isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}for(let t of this._resultFilterSet)await this.addResultFilter(t);this._bPauseScan=!1,this._bNeedOutputOriginalImage=r.bNeedOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&this._isa.startFetching(),this._loopReadVideo(t),e()}),0),this._isa.isCameraEnhancer&&this._isa.getCameraView().setScanLaserVisible(!0)}},Z.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),await this._promiseStartScan))}stopCapturing(){this._checkIsDisposed(),this._isa&&(this._isa.isCameraEnhancer&&(this._isa.getCameraView().setScanLaserVisible(!1),void 0!==this._isa.singleFrameMode&&"disabled"!==this._isa.singleFrameMode)?this._isa.off("singleFrameAcquired",this._singleFrameModeCallbackBind):(this._isa.stopFetching(),this._clearVerifyList(),this._averageProcessintTimeArray=[],this._averageTime=999,this._bPauseScan=!0,this._promiseStartScan=null,this._isa.setColourChannelUsageType(n.CCUT_AUTO)))}async _clearVerifyList(){let t=q();const e=new Xt;return J[t]=async t=>{if(t.success)return e.resolve();{let i=new Error(t.message);return i.stack=t.stack+"\n"+i.stack,e.reject(i)}},Z.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e}async _getIntermediateResult(){this._checkIsDisposed();let t=q();const e=new Xt;return J[t]=async t=>{if(t.success)e.resolve(t.result);else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject(i)}},Z.postMessage({type:"cvr_getIntermediateResult",id:t,instanceID:this._instanceID}),e}async containsTask(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(e){if(this._dynamsoft=!0,this.disposed||this._bPauseScan)return;if(this._isa.isBufferEmpty())if(this._isa.hasNextImageToFetch())for(let t of this._isaStateListenerSet)t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ne.ISS_BUFFER_EMPTY);else if(!this._isa.hasNextImageToFetch())for(let t of this._isaStateListenerSet)t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ne.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||this._isa.isBufferEmpty())try{this._isa.isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=this._isa.fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),this._isa.setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(this._isa.setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=this._isa.getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of this._resultReceiverSet)this._bNeedOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then((async r=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._bPauseScan)return void this._reRunCurrnetFunc(e);r.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of this._resultReceiverSet)if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(r,{isDetectVerifyOpen:this._bOpenDetectVerify,isNormalizeVerifyOpen:this._bOpenNormalizeVerify,isBarcodeVerifyOpen:this._bOpenBarcodeVerify,isLabelVerifyOpen:this._bOpenLabelVerify}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}const n={originalImageHashId:r.originalImageHashId,originalImageTag:r.originalImageTag,errorCode:r.errorCode,errorString:r.errorString};for(let t of this._resultReceiverSet)t.onDecodedBarcodesReceived&&r.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},n),{barcodeResultItems:r.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&r.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},n),{textLineResultItems:r.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&r.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},n),{detectedQuadResultItems:r.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&r.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},n),{normalizedImageResultItems:r.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&r.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},n),{parsedResultItems:r.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(r.items=r.items.filter((t=>!t.isFilter)),r.barcodeResultItems&&(r.barcodeResultItems=r.barcodeResultItems.filter((t=>!t.isFilter))),r.textLineResultItems&&(r.textLineResultItems=r.textLineResultItems.filter((t=>!t.isFilter))),r.detectedQuadResultItems&&(r.detectedQuadResultItems=r.detectedQuadResultItems.filter((t=>!t.isFilter))),r.normalizedImageResultItems&&(r.normalizedImageResultItems=r.normalizedImageResultItems.filter((t=>!t.isFilter))),r.parsedResultItems&&(r.parsedResultItems=r.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(r));const s=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-s;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(e)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(e)}),Math.max(this._minImageCaptureInterval,0))})).catch((t=>{this._isa.stopFetching(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._isa.startFetching(),this._loopReadVideo(e)}),Math.max(this._minImageCaptureInterval,1e3)),"platform error"!==t.message&&setTimeout((()=>{throw t}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;this._checkIsDisposed(),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const n=await this.containsTask(e);let s;if(await at(n),n.includes("dlr")&&!(null===(i=rt.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)&&await(null===(r=rt.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",nt.dlr)),this._dynamsoft=!1,u(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await y(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(this._compressRate=this.maxCvsSideLength/o,i=Math.round(n*this._compressRate),r=Math.round(s*this._compressRate)):(i=n,r=s),this._canvas||(this._canvas=document.createElement("canvas"));const a=this._canvas;return a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(this._compressRate=this.maxCvsSideLength/o,i=Math.round(n*this._compressRate),r=Math.round(s*this._compressRate)):(i=n,r=s),this._canvas||(this._canvas=document.createElement("canvas"));const a=this._canvas;return a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:r,width:n,height:s,stride:o,format:a}=e;let h=q();const l=new Xt;return J[h]=async i=>{var r,n;if(!i.success){let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,l.reject(t)}{const s=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${s}`),t._onLog("worker to main time consume: "+(s-i.workerReturnMsgTime)));try{const t=i.captureResult;e.bytes=i.bytes;for(let i of t.items)0!==this._compressRate&&oe(i,this._compressRate),i.type===lt.CRIT_ORIGINAL_IMAGE?i.imageData=e:i.type===lt.CRIT_NORMALIZED_IMAGE?null===(r=rt.ddn)||void 0===r||r.handleNormalizedImageResultItem(i):i.type===lt.CRIT_PARSED_RESULT&&(null===(n=rt.dcp)||void 0===n||n.handleParsedResultItem(i));if(this._dynamsoft)for(let e of this._resultFilterSet)e.onDecodedBarcodesReceived(t.items),e.onRecognizedTextLinesReceived(t.items),e.onDetectedQuadsReceived(t.items),e.onNormalizedImagesReceived(t.items);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===lt.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===lt.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===lt.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===lt.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===lt.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(t);if(s.barcodeResultItems.length&&(t.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(t.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(t.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(t.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(t.parsedResultItems=s.parsedResultItems),!this._bPauseScan||!this._dynamsoft){const i=t.intermediateResult;if(i){let t=0;for(let r of this._intermediateResultReceiverSet){t++;for(let n of i){if("onTaskResultsReceived"===n.info.callbackName){for(let t of n.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);t===this._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}t&&t.intermediateResult&&delete t.intermediateResult}return this._compressRate=0,l.resolve(t)}catch(i){return l.reject(i)}}},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),Z.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:r,width:n,height:s,stride:o,format:a,templateName:i||"",dynamsoft:this._dynamsoft}},[r.buffer]),l}async initSettings(t){return this._checkIsDisposed(),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.startsWith("{")?this._currentSettings=JSON.parse(t):t=await y(t,"text"):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=q();J[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=q();J[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t){this._checkIsDisposed(),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await at(e),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>E&&"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){this._checkIsDisposed();const i=await this.containsTask(t);return await at(i),await new Promise(((i,r)=>{let n=q();J[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._bNeedOutputOriginalImage=t.bNeedOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},Z.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return this._checkIsDisposed(),await new Promise(((t,e)=>{let i=q();J[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Z.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return this._bufferdItemsManager||(this._bufferdItemsManager=new zt(this)),this._bufferdItemsManager}getIntermediateResultManager(t){if(this._checkIsDisposed(),!t&&0!==ht.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return this._intermediateResultManager||(this._intermediateResultManager=new qt(this)),this._intermediateResultManager}contains(t,e){return function(t,e){let i=e.x,r=e.y,n=t[0].x,s=t[0].y,o=t[1].x,a=t[1].y,h=t[2].x,l=t[2].y,c=t[3].x,u=t[3].y,d=p(i,r,n,s,o,a),f=p(i,r,o,a,h,l),g=p(i,r,h,l,c,u),m=p(i,r,c,u,n,s);function p(t,e,i,r,n,s){return(t-i)*(s-r)-(e-r)*(n-i)}return d>=0&&f>=0&&g>=0&&m>=0||d<=0&&f<=0&&g<=0&&m<=0}(t,e)}async parseRequiredResources(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){this._checkIsDisposed(),this._promiseStartScan&&this.stopCapturing(),this._isa=null,this._resultReceiverSet.clear(),this._isaStateListenerSet.clear(),this._resultFilterSet.clear(),this.bDestroyed=!0;let t=q();J[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Z.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}async _enableResultCrossVerification(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:this._instanceID,body:{verificationEnabled:t}})}))}async _enableResultDeduplication(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})}))}async _setDuplicateForgetTime(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:this._instanceID,body:{duplicateForgetTime:t}})}))}async _getDuplicateForgetTime(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=q();J[r]=async t=>{if(t.success)return e(t.time);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Z.postMessage({type:"cvr_getDuplicateForgetTime",id:r,instanceID:this._instanceID,body:{type:t}})}))}async _setThresholdValue(t,e,i){return await at("ddn"),await new Promise(((r,n)=>{let s=q();J[s]=async t=>{if(t.success)return r();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Z.postMessage({type:"ddn_setThresholdValue",id:s,instanceID:this._instanceID,body:{threshold:t,leftLimit:e,rightLimit:i}})}))}_checkIsDisposed(){if(this.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}},CaptureVisionRouterModule:re,CapturedResultReceiver:class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},get EnumImageSourceState(){return ne},IntermediateResultManager:qt,IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=_t.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const he="undefined"==typeof self,le=(()=>{if(!he&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();null==nt.dce&&(nt.dce=le),ot.dce={wasm:!1,js:!1},rt.dce={};let ce,ue,de,fe,ge;function me(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function pe(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(ce=navigator,ue=ce.userAgent,de=ce.platform,fe=ce.mediaDevices),function(){if(!he){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:ce.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:de,search:"Win"},Mac:{str:de},Linux:{str:de}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||ue,o=n.search||e,a=n.verStr||ue,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||ue,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=ue.indexOf("Windows NT")&&(n="HarmonyOS"),ge={browser:i,version:r,OS:n}}he&&(ge={browser:"ssr",version:0,OS:"ssr"})}();const _e="undefined"!=typeof WebAssembly&&ue&&!(/Safari/.test(ue)&&!/Chrome/.test(ue)&&/\(.+\s11_2_([2-6]).*\)/.test(ue)),ve=!("undefined"==typeof Worker),ye=!(!fe||!fe.getUserMedia),we=async()=>{let t=!1;if(ye)try{(await fe.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===ge.browser&&ge.version>66||"Safari"===ge.browser&&ge.version>13||"OPR"===ge.browser&&ge.version>43||"Edge"===ge.browser&&ge.version;var Ee={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,E,C,T,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=S.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=S,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,r=e.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 x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new b.Point(t.x-e.x,t.y-e.y),n=b.util.rotateVector(r,i);return new b.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),r=b.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=b.util.createVector(t,e),n=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(r,n),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(r,s),n)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,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(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var T=Math.sqrt(1-E/(_*v));i*=T,s*=T}else C=(o===a?-1:1)*Math.sqrt(E/(_*y+v*w));var S=C*i*p/s,I=-C*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,R=n(1,0,(m-S)/i,(p-I)/s),O=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&O>0?O-=2*l:1===a&&O<0&&(O+=2*l);for(var D=Math.ceil(Math.abs(O/l*2)),L=[],M=O/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kC)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],T=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var I,x,A,R=C.length,O=R;R--;)I=(A=1-(f=C[R]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,T[0][R]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,T[1][R]=x;T[0][O]=e,T[1][O]=i,T[0][O+1]=a,T[1][O+1]=h;var D=[{x:y.apply(null,T[0]),y:y.apply(null,T[1])},{x:w.apply(null,T[0]),y:w.apply(null,T[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=b.document.documentElement,n=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=n,!o){if(!f(w,E,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,E,n),void a(t));h()}}(l)})),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,r,n){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},b.util.animate(b.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",T=0,b=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),E.minX=i,E.minY=r,E.viewBoxWidth=n,E.viewBoxHeight=o,y?(E.width=n,E.height=o):(E.width=s(d),E.height=s(f),c=E.width/n,u=E.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),T=E.width-n*c,b=E.height-o*c,"Mid"===p.alignX&&(T/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(T=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+T)+" "+(r*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),E}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function E(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(t){return t.flipX!==t.flipY}function T(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function b(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=E(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),C(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),T(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=E(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),C(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),T(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),C=_(f,y,w),T=e.gestureScale;if(C)return!1;if(T)o=e.scaleX*T,a=e.scaleY*T;else{if(s=E(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=b/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(b))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=E(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=E,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new b.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.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,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.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))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.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(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.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 t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,r=b.util.toFixed,n=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?b.util.loadImage(e,(function(e,n){if(e){var s=new b.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?b.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=b.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new b.Point(r.x,r.y),n=new b.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=b.util.invertTransform(i),n=this.restorePointerVpt(e);return b.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),r=b.util.transformPoint(i,this.viewportTransform),n=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof b.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==r&&(b.Canvas[r]=b.StaticCanvas[r])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(b.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e:e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new b.Point(v(r,s),v(n,o)),h=new b.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return b.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):b.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+b.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=l>y||c>w;v=E||(l<.9*y||c<.9*w)&&y>h&&w>h,E&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof r?r=E[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),n=new b.Point(t.x,t.y),this.angle&&(n=b.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=b.util.cos(r)*n,o=b.util.sin(r)*n;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===b.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=b.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=b.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return b.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=b.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],b.util.enlivenObjectEnlivables(i,i,(function(){var r=new b.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,(function(t,r){e&&e(new b.Image(t,i),r)}),null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,r){var n=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(n["xlink:href"],i,e(r?b.util.object.clone(r):{},n))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){b.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=n,n},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,T||(n+=m[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=T?m[s+3]:n}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=r(1e3*s(b-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(n(i(L*p,2)+i(M*_,2))/1e3)),(S=w[L][M])>0&&(x+=S,A+=S*c[I=4*(F*e+b)],R+=S*c[I+1],O+=S*c[I+2],D+=S*c[I+3]))}d[I=4*(T*a+h)]=A/x,d[I+1]=R/x,d[I+2]=O/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(L=4*(D+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],T+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=T/w,m[v+2]=b/w,m[v+3]=S/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+C*r+o,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,E=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,E=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+E,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);b.Object._fromObject("IText",e,i,"text")}}(),T=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=b.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=T(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:T(r[i-1])}:n?this.styles[t+i]={0:T(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?T(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=T(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=T(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},Ce={};function Te(t){var e=Ce[t];if(void 0!==e)return e.exports;var i=Ce[t]={exports:{}};return Ee[t](i,i.exports,Te),i.exports}Te.d=(t,e)=>{for(var i in e)Te.o(e,i)&&!Te.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},Te.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var be={};(()=>{let t;Te.d(be,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?Te(653).fabric:{version:"5.2.1"}})();var Se,Ie,xe,Ae,Re=be.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Se||(Se={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(Ie||(Ie={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(xe||(xe={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Ae||(Ae={}));const Oe=t=>"number"==typeof t&&!Number.isNaN(t),De=t=>"string"==typeof t;var Le,Me,Fe,Pe,ke,Be;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(ke||(ke={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(Be||(Be={}));class Ne{get mediaType(){return new Map([["rect",Se.DIMT_RECTANGLE],["quad",Se.DIMT_QUADRILATERAL],["text",Se.DIMT_TEXT],["arc",Se.DIMT_ARC],["image",Se.DIMT_IMAGE],["polygon",Se.DIMT_POLYGON],["line",Se.DIMT_LINE],["group",Se.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(me(this,Me,"f")){case Ie.DIS_DEFAULT:return"default";case Ie.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===me(this,Fe,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===me(this,Fe,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),pe(this,Fe,t,"f")}get coordinateBase(){return me(this,Fe,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(Le.add(this),Me.set(this,void 0),Fe.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!Oe(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(Ie.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(Ie.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(Ie.DIS_SELECTED):this.setState(Ie.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){pe(this,Me,t,"f")}getState(){return me(this,Me,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),je=t=>!!De(t)&&""!==t,Ge=u,Ve=d,We=g,Ye=p,He=m,Xe=_,ze=v,Ze=t=>!(!Ue(t)||"id"in t&&!Oe(t.id)||"lineWidth"in t&&!Oe(t.lineWidth)||"fillStyle"in t&&!je(t.fillStyle)||"strokeStyle"in t&&!je(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!je(t.fontFamily)||"fontSize"in t&&!Oe(t.fontSize));class Ke{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(ze(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!Ve(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var qe,Je;class Qe{constructor(){qe.set(this,new Map),Je.set(this,!1)}get disposed(){return me(this,Je,"f")}on(t,e){t=t.toLowerCase();const i=me(this,qe,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else me(this,qe,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=me(this,qe,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=me(this,qe,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=me(this,qe,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){pe(this,Je,!0,"f")}}function $e(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function ti(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function ei(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}qe=new WeakMap,Je=new WeakMap;const ii=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");r.insertAdjacentHTML("beforeend",i);for(let t=0;t0?i-1:r,ui),actionName:"modifyPolygon",pointIndex:i}),t}),{}),pe(this,ni,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new Re.Control({positionHandler:li,actionHandler:di(r>0?r-1:i,ui),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=Re.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){me(this,ni,"f")&&this.setPolygon(me(this,ni,"f"))}setPolygon(t){if(!Ye(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else pe(this,ni,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return me(this,ni,"f")?JSON.parse(JSON.stringify(me(this,ni,"f"))):null}}ni=new WeakMap;si=new WeakMap,oi=new WeakMap;const gi=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else pe(this,_i,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return me(this,_i,"f")?JSON.parse(JSON.stringify(me(this,_i,"f"))):null}}_i=new WeakMap;class $i extends Ne{constructor(t){super(new Re.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(Ie.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(Ie.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class tr{static createDrawingStyle(t){if(!Ze(t))throw new Error("Invalid style definition.");let e,i=tr.USER_START_STYLE_ID;for(;me(tr,vi,"f",yi).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in me(tr,vi,"f",wi))r.hasOwnProperty(t)||(r[t]=me(tr,vi,"f",wi)[t]);return me(tr,vi,"f",yi).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=me(tr,vi,"f",yi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(me(tr,vi,"f",yi).values())))}static _updateDrawingStyle(t,e){if(!Ze(e))throw new Error("Invalid style definition.");const i=me(tr,vi,"f",yi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}vi=tr,tr.STYLE_BLUE_STROKE=1,tr.STYLE_GREEN_STROKE=2,tr.STYLE_ORANGE_STROKE=3,tr.STYLE_YELLOW_STROKE=4,tr.STYLE_BLUE_STROKE_FILL=5,tr.STYLE_GREEN_STROKE_FILL=6,tr.STYLE_ORANGE_STROKE_FILL=7,tr.STYLE_YELLOW_STROKE_FILL=8,tr.STYLE_BLUE_STROKE_TRANSPARENT=9,tr.STYLE_GREEN_STROKE_TRANSPARENT=10,tr.STYLE_ORANGE_STROKE_TRANSPARENT=11,tr.USER_START_STYLE_ID=1024,yi={value:new Map([[tr.STYLE_BLUE_STROKE,{id:tr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[tr.STYLE_GREEN_STROKE,{id:tr.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_ORANGE_STROKE,{id:tr.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_YELLOW_STROKE,{id:tr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[tr.STYLE_BLUE_STROKE_FILL,{id:tr.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_GREEN_STROKE_FILL,{id:tr.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_ORANGE_STROKE_FILL,{id:tr.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_YELLOW_STROKE_FILL,{id:tr.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_BLUE_STROKE_TRANSPARENT,{id:tr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_GREEN_STROKE_TRANSPARENT,{id:tr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[tr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:tr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},wi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(Re.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(Re.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),Re.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},Re.Object.prototype.transparentCorners=!1,Re.Object.prototype.cornerSize=20,Re.Object.prototype.touchCornerSize=100,Re.Object.prototype.cornerColor="rgb(254,142,20)",Re.Object.prototype.cornerStyle="circle",Re.Object.prototype.strokeUniform=!0,Re.Object.prototype.hasBorders=!1,Re.Canvas.prototype.containerClass="",Re.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=Re.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},Re.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();Re.util.addListener(Re.document,"touchend",this._onTouchEnd,{passive:!1}),Re.util.addListener(Re.document,"touchmove",this._onMouseMove,{passive:!1}),Re.util.removeListener(i,r+"down",this._onMouseDown)},Re.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?Re.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class er{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new Re.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case er.DDN_LAYER_ID:r=tr.getDrawingStyle(tr.STYLE_BLUE_STROKE),n=tr.getDrawingStyle(tr.STYLE_BLUE_STROKE_FILL);break;case er.DBR_LAYER_ID:r=tr.getDrawingStyle(tr.STYLE_ORANGE_STROKE),n=tr.getDrawingStyle(tr.STYLE_ORANGE_STROKE_FILL);break;case er.DLR_LAYER_ID:r=tr.getDrawingStyle(tr.STYLE_GREEN_STROKE),n=tr.getDrawingStyle(tr.STYLE_GREEN_STROKE_FILL);break;default:r=tr.getDrawingStyle(tr.STYLE_YELLOW_STROKE),n=tr.getDrawingStyle(tr.STYLE_YELLOW_STROKE_FILL)}for(let t of Ne.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return tr.getDrawingStyle(t.styleId);return tr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=tr.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=tr.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=tr.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,tr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,tr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Ne))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ne.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=tr.getDrawingStyle(t.styleId);else{s=tr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,tr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,tr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ne.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=tr.getDrawingStyle(t.styleId);else{s=tr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,tr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,tr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=Ne.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=Ne.arrStyleSelectors;const r=tr.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&Se.DIMT_RECTANGLE&&r.push("rect"),i&Se.DIMT_QUADRILATERAL&&r.push("quad"),i&Se.DIMT_TEXT&&r.push("text"),i&Se.DIMT_ARC&&r.push("arc"),i&Se.DIMT_IMAGE&&r.push("image"),i&Se.DIMT_POLYGON&&r.push("polygon"),i&Se.DIMT_LINE&&r.push("line");const n=[];e&Ie.DIS_DEFAULT&&n.push("default"),e&Ie.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}er.DDN_LAYER_ID=1,er.DBR_LAYER_ID=2,er.DLR_LAYER_ID=3,er.USER_DEFINED_LAYER_BASE_ID=100,er.TIP_LAYER_ID=999;class ir{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new er(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class rr extends mi{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),Ei.set(this,void 0),Ci.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&pe(this,Ci,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),me(this,Ei,"f")),"f")}getDuration(){return me(this,Ei,"f")}}Ei=new WeakMap,Ci=new WeakMap;class nr{constructor(){Ti.add(this),bi.set(this,void 0),Si.set(this,void 0),Ii.set(this,void 0),xi.set(this,!0),this._drawingLayerManager=new ir}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=er.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==er.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==er.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Ue(e=t)&&He(e.topLeftPoint)&&Oe(e.width))||e.width<=0||!Oe(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;pe(this,bi,JSON.parse(JSON.stringify(t)),"f"),me(this,bi,"f").coordinateBase||(me(this,bi,"f").coordinateBase="view"),pe(this,Ii,t.duration,"f"),me(this,Ti,"m",Di).call(this)}getTipConfig(){return me(this,bi,"f")?me(this,bi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),pe(this,xi,t,"f")}isTipVisible(){return me(this,xi,"f")}updateTipMessage(t){if(!me(this,bi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=tr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(er.TIP_LAYER_ID)||this._createDrawingLayer(er.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=me(this,Ti,"m",Ai).call(this,t,me(this,bi,"f").topLeftPoint.x,me(this,bi,"f").topLeftPoint.y,me(this,bi,"f").width,me(this,bi,"f").coordinateBase,this._tipStyleId),me(this,Ti,"m",Ri).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",me(this,xi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),me(this,Si,"f")&&clearTimeout(me(this,Si,"f")),me(this,Ii,"f")>=0&&pe(this,Si,setTimeout((()=>{me(this,Ti,"m",Oi).call(this)}),me(this,Ii,"f")),"f")}}bi=new WeakMap,Si=new WeakMap,Ii=new WeakMap,xi=new WeakMap,Ti=new WeakSet,Ai=function(t,e,i,r,n,s){const o=new rr(t,e,i,r,s);return o.coordinateBase=n,o},Ri=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},Oi=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},Di=function(){if(!this._tip)return;const t=me(this,bi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class sr extends HTMLElement{constructor(){super(),Li.set(this,void 0);const t=document.createElement("template").content,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),pe(this,Li,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t.cloneNode(!0))}getWrapper(){return me(this,Li,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}Li=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",sr);class or extends HTMLElement{constructor(){super();const t=window._dce_default_template.content;this.attachShadow({mode:"open"}).appendChild(t.cloneNode(!0))}showScanLaser(){const t=this.shadowRoot.querySelector(".dce-scanlight");t&&(t.style.display="")}hideScanLaser(){const t=this.shadowRoot.querySelector(".dce-scanlight");t&&(t.style.display="none")}getElement(t){return this.shadowRoot.querySelector(t)}getVideoContainer(){return this.shadowRoot.querySelector(".dce-video-container")}getScanAreaEl(){return this.shadowRoot.querySelector(".dce-scanarea")}getScanLightEl(){return this.shadowRoot.querySelector(".dce-scanlight")}getLoadingBackgroundEl(){return this.shadowRoot.querySelector(".dce-bg-loading")}getCameraBackgroundEl(){return this.shadowRoot.querySelector(".dce-bg-camera")}getCameraSelectEl(){return this.shadowRoot.querySelector(".dce-sel-camera")}getResolutionSelectEl(){return this.shadowRoot.querySelector(".dce-sel-resolution")}getResolutionOptionEl(){return this.shadowRoot.querySelector(".dce-opt-gotResolution")}getCloseBtnEl(){return this.shadowRoot.querySelector(".dce-btn-close")}getDLRSelectEl(){return this.shadowRoot.querySelector(".dlr-sel-minletter")}getDLROptionEl(){return this.shadowRoot.querySelector(".dlr-opt-gotMinLtr")}}class ar extends nr{static get engineResourcePath(){return ht.engineResourcePaths.dce}static set defaultUIElementURL(t){ar._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=ar._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",ar.engineResourcePath)}static async createInstance(t){customElements.get(ar.uiComponentName)||customElements.define(ar.uiComponentName,or);const e=new ar;return await e.setUIElement(t||ar.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==me(this,Vi,"f")){if(pe(this,Vi,t,"f"),me(this,Mi,"m",Hi).call(this))pe(this,Bi,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!me(this,Bi,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ge.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),pe(this,Bi,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}me(this,Mi,"m",Hi).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return me(this,Vi,"f")}get disposed(){return me(this,Yi,"f")}constructor(){super(),Mi.add(this),Fi.set(this,void 0),Pi.set(this,void 0),ki.set(this,void 0),this.containerClassName="dce-video-container",Bi.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,Ni.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Ui.set(this,!1),ji.set(this,!1),Gi.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{me(this,Mi,"m",qi).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&me(this,Mi,"m",Ki).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{ar._onLog&&ar._onLog("window resize event triggered."),me(this,Gi,"f").width===document.documentElement.clientWidth&&me(this,Gi,"f").height===document.documentElement.clientHeight||(me(this,Gi,"f").width=document.documentElement.clientWidth,me(this,Gi,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Vi.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!me(this,Mi,"m",Hi).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Wi.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>ar._transformCoordinates(t,i,r,n,s,o,a)));const c=new Qi({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),me(this,Wi,"f").push(c)};let m,p;for(let t of a)switch(t.type){case lt.CRIT_ORIGINAL_IMAGE:break;case lt.CRIT_BARCODE:m=this.getDrawingLayer(er.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,tr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case lt.CRIT_TEXT_LINE:m=this.getDrawingLayer(er.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,tr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case lt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(er.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],tr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case lt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(er.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],tr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case lt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},Yi.set(this,!1),this.eventHandler=new Qe,this.eventHandler.on("content:updated",(()=>{me(this,Fi,"f")&&clearTimeout(me(this,Fi,"f")),pe(this,Fi,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{me(this,Pi,"f")&&clearTimeout(me(this,Pi,"f")),pe(this,Pi,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){t instanceof HTMLTemplateElement?(window._dce_default_template=t,this.UIElement=new or):this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if(e="string"==typeof t?await ii(t):t,e instanceof HTMLDivElement&&0==e.childElementCount){const t=await ii(ar.defaultUIElementURL);t instanceof HTMLTemplateElement?(window._dce_default_template=t,e.append(new or)):e.append(t),this._setUIElement(e)}else this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let e,i=this.UIElement;if(i instanceof or?e=i.getElement(`.${this.containerClassName}`):i instanceof HTMLDivElement&&1===i.childElementCount&&i.firstElementChild instanceof or?(e=i.firstElementChild.getElement(`.${this.containerClassName}`),i=i.firstElementChild):e=i.classList.contains(this.containerClassName)?i:i.querySelector(`.${this.containerClassName}`),!e)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new sr,e.appendChild(this._innerComponent),me(this,Mi,"m",Hi).call(this));else{const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ge.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),pe(this,Bi,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(i instanceof or?(this._selRsl=i.getElement(".dce-sel-resolution"),this._selMinLtr=i.getElement(".dlr-sel-minletter"),this._divScanArea=i.getElement(".dce-scanarea"),this._divScanLight=i.getElement(".dce-scanlight"),this._bgLoading=i.getElement(".dce-bg-loading"),this._bgCamera=i.getElement(".dce-bg-camera"),this._selCam=i.getElement(".dce-sel-camera"),this._optGotRsl=i.getElement(".dce-opt-gotResolution"),this._btnClose=i.getElement(".dce-btn-close"),this._optGotMinLtr=i.getElement(".dlr-opt-gotMinLtr")):(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr")),this._selRsl&&(this._hideDefaultSelection||me(this,Mi,"m",Hi).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||me(this,Mi,"m",Hi).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||me(this,Mi,"m",qi).call(this),me(this,Mi,"m",Hi).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),me(this,Mi,"m",Hi).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;ar._onLog&&ar._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const e=null===(t=this._innerComponent)||void 0===t?void 0:t.getWrapper();e&&this._resizeObserver.observe(e)}me(this,Gi,"f").width=document.documentElement.clientWidth,me(this,Gi,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;me(this,Mi,"m",Hi).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),me(this,Mi,"m",qi).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,pe(this,Bi,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(!this._selCam)return;let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"))}getVideoElement(){return me(this,Bi,"f")}isVideoLoaded(){return!!me(this,Bi,"f")&&4==me(this,Bi,"f").readyState}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!me(this,Bi,"f"))return;if(me(this,Bi,"f").style.objectFit=t,me(this,Mi,"m",Hi).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}me(this,Mi,"m",Ji).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(me(this,Mi,"m",Hi).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=me(this,Bi,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=me(this,Bi,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=Ke.convert(this.scanRegion,t.width,t.height);pe(this,Ni,e,"f"),me(this,ki,"f")&&clearTimeout(me(this,ki,"f")),pe(this,ki,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}me(this,Mi,"m",Xi).call(this,t,e),me(this,Mi,"m",Ji).call(this,t,e)}),0),"f")}getConvertedRegion(){return me(this,Ni,"f")}setScanRegion(t){if(null!=t&&!Ve(t)&&!ze(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=me(this,Bi,"f").videoWidth,i=me(this,Bi,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=me(this,Bi,"f").videoWidth,e=me(this,Bi,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),me(this,Wi,"f").length=0}dispose(){this._unbindUI(),delete window._dce_default_template,this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function hr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function lr(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}Fi=new WeakMap,Pi=new WeakMap,ki=new WeakMap,Bi=new WeakMap,Ni=new WeakMap,Ui=new WeakMap,ji=new WeakMap,Gi=new WeakMap,Vi=new WeakMap,Wi=new WeakMap,Yi=new WeakMap,Mi=new WeakSet,Hi=function(){return"disabled"!==this._singleFrameMode},Xi=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},zi=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Zi=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Ki=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},qi=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Ji=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===mr.browser&&mr.version>13||"OPR"===mr.browser&&mr.version>43||"Edge"===mr.browser&&mr.version,"function"==typeof SuppressedError&&SuppressedError;let vr=class t{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,i,r){return t.multiply(e,[1,0,0,0,1,0,i,r,1])}static rotate(e,i){var r=Math.cos(i),n=Math.sin(i);return t.multiply(e,[r,-n,0,n,r,0,0,0,1])}static scale(e,i,r){return t.multiply(e,[i,0,0,0,r,0,0,0,1])}};var yr,wr,Er,Cr,Tr,br,Sr,Ir,xr,Ar,Rr,Or,Dr,Lr,Mr,Fr,Pr,kr,Br,Nr,Ur,jr,Gr,Vr,Wr,Yr,Hr,Xr,zr,Zr,Kr,qr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(yr||(yr={}));class vn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(_r(vn,wr,!1,"f",Er),!1):(_r(vn,wr,!0,"f",Er),!0)}get disposed(){return pr(this,xr,"f")}constructor(){Cr.set(this,yr.RGBA),Tr.set(this,null),br.set(this,null),Sr.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Ir.set(this,null),xr.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==pr(vn,wr,"f",Er)&&vn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!pr(vn,wr,"f",Er))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;vn._onLog&&(o=Date.now(),vn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=yr.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!pr(vn,wr,"f",Er)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){vn._onLog&&vn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);_r(this,br,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),_r(this,Sr,e(t),"f"),_r(this,Tr,i(t),"f"),_r(this,Cr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[yr.GREY,yr.GREY32].includes(p)?1:0);let m,_,v=vr.translate(vr.identity(),-1,-1);v=vr.scale(v,2,2),v=vr.scale(v,1/t.canvas.width,1/t.canvas.height),m=vr.translate(v,u,d),m=vr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=vr.translate(vr.identity(),a/i,h/r),_=vr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,pr(this,Tr,"f"),e),v(t,pr(this,br,"f"),pr(this,Sr,"f"),pr(this,Tr,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){vn._onLog&&vn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return vn._onLog&&vn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===yr.GREY?yr.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return vn._onLog&&vn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(vn._onLog&&(n=Date.now(),vn._onLog("transformPixelFormat(), START: "+n)),e===i)return vn._onLog&&vn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[yr.RGBA,yr.RBGA,yr.GRBA,yr.GBRA,yr.BRGA,yr.BGRA];if(o.includes(e))if(i===yr.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;vn._onLog&&(s=Date.now(),vn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=yr.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),pr(vn,wr,"f",Er)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){vn._onLog&&vn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===yr.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||n.apply(i.target,r)}),0);else try{s=n.apply(i.target,r)}catch(t){}if(!0===s)break}}}dispose(){lr(this,Rr,!0,"f")}}Ar=new WeakMap,Rr=new WeakMap;const wn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class En{static get version(){return"2.0.7"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(mr.OS))return En.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(mr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a){await m;try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!hr(this,Wr,"f"))return"closed";if("pending"===hr(this,Wr,"f"))return"opening";if("fulfilled"===hr(this,Wr,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?En.isStorageAvailable("localStorage")?lr(this,Ur,!0,"f"):(lr(this,Ur,!1,"f"),console.warn("Local storage is unavailable")):lr(this,Ur,!1,"f")}get ifSaveLastUsedCamera(){return hr(this,Ur,"f")}get isVideoPlaying(){return!(!hr(this,Lr,"f")||hr(this,Lr,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=hr(this,Kr,"f"))||void 0===e||e.removeEventListener("click",hr(this,Zr,"f")),null===(i=hr(this,Kr,"f"))||void 0===i||i.removeEventListener("touchend",hr(this,Zr,"f")),null===(r=hr(this,Kr,"f"))||void 0===r||r.removeEventListener("touchmove",hr(this,zr,"f")),lr(this,Kr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(mr.OS)?(t.addEventListener("touchend",hr(this,Zr,"f")),t.addEventListener("touchmove",hr(this,zr,"f"))):t.addEventListener("click",hr(this,Zr,"f")))}get tapFocusEventBoundEl(){return hr(this,Kr,"f")}get disposed(){return hr(this,sn,"f")}constructor(t){var e,i;Dr.add(this),Lr.set(this,null),Mr.set(this,void 0),Fr.set(this,(()=>{"opened"===this.state&&hr(this,$r,"f").fire("resumed",null,{target:this,async:!1})})),Pr.set(this,(()=>{hr(this,$r,"f").fire("paused",null,{target:this,async:!1})})),kr.set(this,void 0),Br.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Nr.set(this,void 0),Ur.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,jr.set(this,void 0),Gr.set(this,!0),Vr.set(this,void 0),Wr.set(this,void 0),Yr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},Hr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(hr(this,Lr,"f")).objectFit,s=this.getResolution(),o=hr(this,Lr,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=hr(this,Lr,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},Xr.set(this,!1),zr.set(this,(()=>{lr(this,Xr,!0,"f")})),Zr.set(this,(async t=>{var e;if(hr(this,Xr,"f"))return void lr(this,Xr,!1,"f");if(!hr(this,Hr,"f"))return;if(!this.isVideoPlaying)return;if(!hr(this,Mr,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;En._onLog&&(c=Date.now());try{await hr(this,Dr,"m",mn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(En._onLog)throw En._onLog(t),t}En._onLog&&En._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;En._onLog&&En._onLog("Back to continuous focus."),null===(t=hr(this,Mr,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),hr(this,$r,"f").fire("tapfocus",null,{target:this,async:!1})})),Kr.set(this,null),qr.set(this,1),Jr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!hr(this,Lr,"f"))return;const t=hr(this,qr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)hr(this,Lr,"f").style.transform="";else{const e=window.getComputedStyle(hr(this,Lr,"f")).objectFit,i=hr(this,Lr,"f").videoWidth,r=hr(this,Lr,"f").videoHeight,{width:n,height:s}=hr(this,Lr,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-hr(this,Jr,"f").x),c=h*(1-1/t)*(r/2-hr(this,Jr,"f").y);hr(this,Lr,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},Qr.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===yr.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(En._onLog&&En._onLog("document visible. video paused: "+(null===(t=hr(this,Lr,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){En._onLog&&En._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){En._onLog&&En._onLog("document visible. 1st resume video failed, try open instead.")}e||await hr(this,Dr,"m",cn).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){En._onLog&&En._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){En._onLog&&En._onLog("document visible. 2rd resume video failed, try open instead.")}e||await hr(this,Dr,"m",cn).call(this)}}}else"hidden"===document.visibilityState&&(En._onLog&&En._onLog("document hidden. video paused: "+(null===(e=hr(this,Lr,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),sn.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{En.onWarning&&En.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),lr(this,$r,new yn,"f"),this.imageDataGetter=new vn,document.addEventListener("visibilitychange",hr(this,nn,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",hr(this,Fr,"f")),t.addEventListener("pause",hr(this,Pr,"f")),lr(this,Lr,t,"f")}getVideoEl(){return hr(this,Lr,"f")}releaseVideoEl(){var t,e;null===(t=hr(this,Lr,"f"))||void 0===t||t.removeEventListener("play",hr(this,Fr,"f")),null===(e=hr(this,Lr,"f"))||void 0===e||e.removeEventListener("pause",hr(this,Pr,"f")),lr(this,Lr,null,"f")}isVideoLoaded(){return!!hr(this,Lr,"f")&&4==hr(this,Lr,"f").readyState}async open(){if(hr(this,Vr,"f")&&!hr(this,Gr,"f")){if("pending"===hr(this,Wr,"f"))return hr(this,Vr,"f");if("fulfilled"===hr(this,Wr,"f"))return}hr(this,$r,"f").fire("before:open",null,{target:this}),await hr(this,Dr,"m",cn).call(this),hr(this,$r,"f").fire("played",null,{target:this,async:!1}),hr(this,$r,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;hr(this,$r,"f").fire("before:close",null,{target:this});const t=hr(this,Vr,"f");if(hr(this,Dr,"m",dn).call(this),t&&"pending"===hr(this,Wr,"f")){try{await t}catch(t){}if(!1===hr(this,Gr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}lr(this,Vr,null,"f"),lr(this,Wr,null,"f"),hr(this,$r,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");hr(this,Lr,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await hr(this,Lr,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof hr(this,kr,"f").video&&(hr(this,kr,"f").video={}),delete hr(this,kr,"f").video.facingMode,hr(this,kr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&hr(this,Gr,"f"))){hr(this,$r,"f").fire("before:camera:change",[],{target:this,async:!1}),await hr(this,Dr,"m",un).call(this);try{this.resetSoftwareScale()}catch(t){}return hr(this,Br,"f")}}async switchToFrontCamera(t){if("object"!=typeof hr(this,kr,"f").video&&(hr(this,kr,"f").video={}),(null==t?void 0:t.resolution)&&(hr(this,kr,"f").video.width={ideal:t.resolution.width},hr(this,kr,"f").video.height={ideal:t.resolution.height}),delete hr(this,kr,"f").video.deviceId,hr(this,kr,"f").video.facingMode={exact:"user"},lr(this,Nr,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&hr(this,Gr,"f"))){hr(this,$r,"f").fire("before:camera:change",[],{target:this,async:!1}),hr(this,Dr,"m",un).call(this);try{this.resetSoftwareScale()}catch(t){}return hr(this,Br,"f")}}getCamera(){var t;if(hr(this,Br,"f"))return hr(this,Br,"f");{let e=(null===(t=hr(this,kr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof hr(this,kr,"f").video&&(hr(this,kr,"f").video={}),i?(hr(this,kr,"f").video.width={exact:t},hr(this,kr,"f").video.height={exact:e}):(hr(this,kr,"f").video.width={ideal:t},hr(this,kr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&hr(this,Gr,"f"))return null;hr(this,$r,"f").fire("before:resolution:change",[],{target:this,async:!1}),await hr(this,Dr,"m",un).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&hr(this,Lr,"f"))return{width:hr(this,Lr,"f").videoWidth,height:hr(this,Lr,"f").videoHeight};if(hr(this,Mr,"f")){const t=hr(this,Mr,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:hr(this,Lr,"f").videoWidth,height:hr(this,Lr,"f").videoHeight};{const t={width:0,height:0};let e=hr(this,kr,"f").video.width||0,i=hr(this,kr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=hr(this,en,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=hr(this,Br,"f"))||void 0===u?void 0:u.deviceId;let e=hr(this,en,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],hr(this,en,"f").set(d,e),lr(this,Yr,!0,"f");try{for(let t of this.detectedResolutions){await hr(this,Mr,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),hr(this,Dr,"m",an).call(this);const i=hr(this,Mr,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw hr(this,Dr,"m",dn).call(this),lr(this,Yr,!1,"f"),t}try{await hr(this,Dr,"m",cn).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{lr(this,Yr,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=hr(this,kr,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=hr(this,kr,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=hr(this,kr,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=hr(this,en,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],hr(this,en,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");lr(this,kr,JSON.parse(JSON.stringify(t)),"f"),lr(this,Nr,null,"f"),e&&hr(this,Dr,"m",un).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(hr(this,kr,"f")))}resetMediaStreamConstraints(){lr(this,kr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return hr(this,Mr,"f").getCapabilities?hr(this,Mr,"f").getCapabilities():{}}getCameraSettings(){if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return hr(this,Mr,"f").getSettings()}async turnOnTorch(){if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await hr(this,Mr,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await hr(this,Mr,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=wn(t,r.min,r.step,r.max)),await hr(this,Mr,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=wn(t,r.min,r.step,r.max)),await hr(this,Mr,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await hr(this,Mr,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=wn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await hr(this,Mr,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await hr(this,Dr,"m",mn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await hr(this,Mr,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){lr(this,Hr,!0,"f")}disableTapToFocus(){lr(this,Hr,!1,"f")}isTapToFocusEnabled(){return hr(this,Hr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?hr(this,Dr,"m",pn).call(this,t.centerPoint):this.resetScaleCenter();try{if(hr(this,Dr,"m",_n).call(this,hr(this,Jr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*hr(this,qr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!hr(this,Mr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=wn(t,r.min,r.step,r.max)),await hr(this,Mr,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&hr(this,Dr,"m",pn).call(this,e),lr(this,qr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return hr(this,qr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();lr(this,Jr,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(hr(this,Yr,"f"))return null;const e=Date.now();En._onLog&&En._onLog("getFrameData() START: "+e);const i=hr(this,Lr,"f").videoWidth,r=hr(this,Lr,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=yr.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=hr(this,qr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=hr(this,Jr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(hr(this,Lr,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return En._onLog&&En._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:hr(this,Qr,"f")}}on(t,e){if(!hr(this,tn,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);hr(this,$r,"f").on(t,e)}off(t,e){hr(this,$r,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),hr(this,$r,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",hr(this,nn,"f")),lr(this,sn,!0,"f")}}var Cn,Tn,bn,Sn,In,xn,An,Rn,On,Dn,Ln,Mn,Fn,Pn,kn,Bn,Nn,Un,jn,Gn,Vn,Wn,Yn,Hn,Xn,zn,Zn,Kn,qn,Jn,Qn,$n,ts;Lr=new WeakMap,Mr=new WeakMap,Fr=new WeakMap,Pr=new WeakMap,kr=new WeakMap,Br=new WeakMap,Nr=new WeakMap,Ur=new WeakMap,jr=new WeakMap,Gr=new WeakMap,Vr=new WeakMap,Wr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,Zr=new WeakMap,Kr=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,tn=new WeakMap,en=new WeakMap,rn=new WeakMap,nn=new WeakMap,sn=new WeakMap,Dr=new WeakSet,on=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(hr(this,Nr,"f"))delete t.video.facingMode,t.video.deviceId={exact:hr(this,Nr,"f")};else if(this.ifSaveLastUsedCamera&&En.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(mr.OS)?(await this._getCameras(!1),hr(this,Dr,"m",an).call(this),e=En.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(mr.OS)||(await this._getCameras(!1),hr(this,Dr,"m",an).call(this),e=En.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},an=function(){if(hr(this,Gr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},hn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{En._onLog&&En._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),hr(this,Dr,"m",an).call(this));try{En._onLog&&En._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),hr(this,Dr,"m",an).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,En._onLog&&En._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},ln=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),lr(this,Mr,null,"f")},cn=async function(){lr(this,Gr,!1,"f");const t=lr(this,jr,Symbol(),"f");if(hr(this,Vr,"f")&&"pending"===hr(this,Wr,"f")){try{await hr(this,Vr,"f")}catch(t){}hr(this,Dr,"m",an).call(this)}if(t!==hr(this,jr,"f"))return;const e=lr(this,Vr,(async()=>{lr(this,Wr,"pending","f");try{if(this.videoSrc){if(!hr(this,Lr,"f"))throw new Error("'videoEl' should be set.");await En.playVideo(hr(this,Lr,"f"),this.videoSrc,this.cameraOpenTimeout),hr(this,Dr,"m",an).call(this)}else{let t=await hr(this,Dr,"m",on).call(this);hr(this,Dr,"m",ln).call(this);let e=await hr(this,Dr,"m",hn).call(this,t);await this._getCameras(!1),hr(this,Dr,"m",an).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=hr(this,kr,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(hr(this,Nr,"f")||this.ifSaveLastUsedCamera&&En.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=En.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await hr(this,Dr,"m",hn).call(this,t),hr(this,Dr,"m",an).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(lr(this,Nr,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&En.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",hr(this,Nr,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),hr(this,Lr,"f")&&(await En.playVideo(hr(this,Lr,"f"),e,this.cameraOpenTimeout),hr(this,Dr,"m",an).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&lr(this,Mr,s[0],"f"),lr(this,Br,n,"f")}}catch(t){throw hr(this,Dr,"m",dn).call(this),lr(this,Wr,null,"f"),t}lr(this,Wr,"fulfilled","f")})(),"f");return e},un=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=hr(this,Br,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await hr(this,Dr,"m",cn).call(this);const r=this.getResolution();e&&e!==hr(this,Br,"f").deviceId&&hr(this,$r,"f").fire("camera:changed",[hr(this,Br,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||hr(this,$r,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),hr(this,$r,"f").fire("played",null,{target:this,async:!1})},dn=function(){hr(this,Dr,"m",ln).call(this),lr(this,Br,null,"f"),hr(this,Lr,"f")&&(hr(this,Lr,"f").srcObject=null,this.videoSrc&&(hr(this,Lr,"f").pause(),hr(this,Lr,"f").currentTime=0)),lr(this,Gr,!0,"f");try{this.resetSoftwareScale()}catch(t){}},fn=async function t(e,i){const r=t=>{if(!hr(this,Mr,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){hr(this,Mr,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=wn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await hr(this,Mr,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();if(s>=l.width||o>=l.height)throw new Error("Invalid area.");s+a>l.width&&(a=l.width-s),o+h>l.height&&(h=l.height-o),s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(hr(this,Lr,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:yr.RGBA,bufferContainer:d}))return hr(this,Dr,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await hr(this,Dr,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await hr(this,Dr,"m",fn).call(this,e,c);if(a>h)return await hr(this,Dr,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await hr(this,Dr,"m",t).call(this,e,o,a,c,h);let u=await hr(this,Dr,"m",fn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==hr(this,qr,"f")){const t=hr(this,qr,"f"),e=hr(this,Jr,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=wn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=wn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=wn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await hr(this,Dr,"m",fn).call(this,t,s),a=await hr(this,Dr,"m",fn).call(this,t,n),h=await hr(this,Dr,"m",fn).call(this,t,r);if(a>h&&ho&&a>o){let e=await hr(this,Dr,"m",fn).call(this,t,i);const n=await hr(this,Dr,"m",gn).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await hr(this,Dr,"m",gn).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},pn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");lr(this,Jr,{x:i,y:r},"f")},_n=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},En.browserInfo=mr,En.onWarning=null===(Or=null===window||void 0===window?void 0:window.console)||void 0===Or?void 0:Or.warn;class es{constructor(t){Cn.add(this),Tn.set(this,void 0),bn.set(this,0),Sn.set(this,void 0),In.set(this,0),xn.set(this,!1),pe(this,Tn,t,"f")}startCharging(){me(this,xn,"f")||(es._onLog&&es._onLog("start charging."),me(this,Cn,"m",Rn).call(this),pe(this,xn,!0,"f"))}stopCharging(){me(this,Sn,"f")&&clearTimeout(me(this,Sn,"f")),me(this,xn,"f")&&(es._onLog&&es._onLog("stop charging."),pe(this,bn,Date.now()-me(this,In,"f"),"f"),pe(this,xn,!1,"f"))}}Tn=new WeakMap,bn=new WeakMap,Sn=new WeakMap,In=new WeakMap,xn=new WeakMap,Cn=new WeakSet,An=function(){ht.cfd(1),es._onLog&&es._onLog("charge 1.")},Rn=function t(){0==me(this,bn,"f")&&me(this,Cn,"m",An).call(this),pe(this,In,Date.now(),"f"),me(this,Sn,"f")&&clearTimeout(me(this,Sn,"f")),pe(this,Sn,setTimeout((()=>{pe(this,bn,0,"f"),me(this,Cn,"m",t).call(this)}),me(this,Tn,"f")-me(this,bn,"f")),"f")};const is=new Map([[s.IPF_GRAYSCALED,yr.GREY],[s.IPF_ABGR_8888,yr.RGBA],[s.IPF_ARGB_8888,yr.BGRA]]),rs=new Map([[yr.GREY,s.IPF_GRAYSCALED],[yr.RGBA,s.IPF_ABGR_8888],[yr.BGRA,s.IPF_ARGB_8888]]),ns="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class ss extends O{static set _onLog(t){pe(ss,Dn,t,"f",Ln),En._onLog=t,es._onLog=t}static get _onLog(){return me(ss,Dn,"f",Ln)}static async detectEnvironment(){return await(async()=>({wasm:_e,worker:ve,getUserMedia:ye,camera:await we(),browser:ge.browser,version:ge.version,OS:ge.OS}))()}static async testCameraAccess(){const t=await En.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof ar))throw new TypeError("Invalid view.");if(null===(e=rt.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=rt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await ht.loadWasm(["license"]),await rt.license.dynamsoft()}const r=new ss(t);return ss.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ss.onWarning&&ss.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ss.onWarning&&ss.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return me(this,Mn,"f").getVideoEl()}set videoSrc(t){if(!me(this,Mn,"f"))throw new Error("Camera manager is null.");me(this,Fn,"f")&&(me(this,Fn,"f")._hideDefaultSelection=!0),me(this,Mn,"f").videoSrc=t}get videoSrc(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!me(this,Mn,"f"))throw new Error("Camera manager is null.");me(this,Mn,"f").ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!me(this,Mn,"f"))throw new Error("Camera manager is null.");me(this,Mn,"f").ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!me(this,Mn,"f"))throw new Error("Camera manager is null.");me(this,Mn,"f").cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");pe(this,Nn,t,"f")}get singleFrameMode(){return me(this,Nn,"f")}get _isFetchingStarted(){return me(this,Yn,"f")}get disposed(){return me(this,Kn,"f")}constructor(t){if(super(),On.add(this),Mn.set(this,void 0),Fn.set(this,void 0),Pn.set(this,"closed"),kn.set(this,void 0),Bn.set(this,!1),Nn.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&me(this,Fn,"f")&&!me(this,Fn,"f").disposed&&await this.selectCamera(me(this,Fn,"f")._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!me(this,Fn,"f")||me(this,Fn,"f").disposed)return;let t,e;if(me(this,Fn,"f")._selRsl&&-1!=me(this,Fn,"f")._selRsl.selectedIndex){let i=me(this,Fn,"f")._selRsl.options[me(this,Fn,"f")._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&me(this,Fn,"f")&&!me(this,Fn,"f").disposed&&this.close()},Un.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=me(this,Mn,"f").imageDataGetter.getImageData(t,e,i,s,{pixelFormat:is.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===yr.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:rs.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:gt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:me(this,jn,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=me(this,Fn,"f")?me(this,Fn,"f").getConvertedRegion():Ke.convert(me(this,Vn,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=me(this,Un,"f").call(this,t,t.width,t.height,e);me(this,kn,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},jn.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===s.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=me(this,Mn,"f").getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");me(this,Fn,"f")&&!me(this,Fn,"f").disposed?(this.video.style.transform=1===t?"":`scale(${t})`,me(this,Fn,"f")._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ge.OS)?me(this,Mn,"f").setResolution(1280,720):me(this,Mn,"f").setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&this.setCameraView(t),this._on("before:camera:change",(()=>{me(this,Zn,"f").stopCharging();const t=me(this,Fn,"f");t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=me(this,Fn,"f");t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{me(this,Zn,"f").stopCharging();const t=me(this,Fn,"f");t&&t.disposed})),this._on("resumed",(()=>{const t=me(this,Fn,"f");t&&t.disposed})),this._on("tapfocus",(()=>{me(this,Xn,"f").tapToFocus&&me(this,Zn,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(me(this,On,"m",qn).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;ss._onLog&&(ss._onLog("intermediateResultUnits:"),ss._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===_t.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===_t.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ss._onLog&&(ss._onLog("hasLocalizedBarcodes:"),ss._onLog(h)),me(this,Xn,"f").autoZoom||me(this,Xn,"f").enhancedFocus)if(a)me(this,zn,"f").autoZoomInFrameArray.length=0,me(this,zn,"f").autoZoomOutFrameCount=0,me(this,zn,"f").frameArrayInIdealZoom.length=0,me(this,zn,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),me(this,Xn,"f").autoZoom&&me(this,Zn,"f").startCharging()},a=async t=>{await this.setFocus(t),me(this,Xn,"f").enhancedFocus&&me(this,Zn,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-me(this,zn,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+me(this,zn,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-me(this,zn,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+me(this,zn,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}ss._onLog&&(ss._onLog("detectionArea:"),ss._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=ti(a.y-i)>0&&ti(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(ei([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||ei([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||ei([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||ei([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{ar._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(ss._debug&&me(this,Fn,"f")){const t=this.__layer||(this.__layer=me(this,Fn,"f")._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=tr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new fi({points:i},e);t.addDrawingItems([n])}}}if(ss._onLog&&(ss._onLog("intersectedResults:"),ss._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==ns.BF_QR_CODE||t.possibleFormats==ns.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==ns.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),me(this,zn,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=me(this,zn,"f").autoZoomInFrameLimit[1]){me(this,zn,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,me(this,zn,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/me(this,zn,"f").autoZoomInMaxTimes),me(this,zn,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(me(this,zn,"f").minValue,u),u=Math.min(me(this,zn,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(me(this,zn,"f").autoZoomInFrameArray.length=0,me(this,zn,"f").frameArrayInIdealZoom.push(!0),me(this,zn,"f").frameArrayInIdealZoom.splice(0,me(this,zn,"f").frameArrayInIdealZoom.length-me(this,zn,"f").frameLimitInIdealZoom[0]),me(this,zn,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=me(this,zn,"f").frameLimitInIdealZoom[1]&&(me(this,zn,"f").frameArrayInIdealZoom.length=0,me(this,Xn,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!me(this,Xn,"f").autoZoom&&me(this,Xn,"f").enhancedFocus&&(me(this,zn,"f").autoFocusFrameArray.push(!0),me(this,zn,"f").autoFocusFrameArray.splice(0,me(this,zn,"f").autoFocusFrameArray.length-me(this,zn,"f").autoFocusFrameLimit[0]),me(this,zn,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=me(this,zn,"f").autoFocusFrameLimit[1])){me(this,zn,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(me(this,Xn,"f").autoZoom){if(me(this,zn,"f").autoZoomInFrameArray.push(!1),me(this,zn,"f").autoZoomInFrameArray.splice(0,me(this,zn,"f").autoZoomInFrameArray.length-me(this,zn,"f").autoZoomInFrameLimit[0]),me(this,zn,"f").autoZoomOutFrameCount++,me(this,zn,"f").frameArrayInIdealZoom.push(!1),me(this,zn,"f").frameArrayInIdealZoom.splice(0,me(this,zn,"f").frameArrayInIdealZoom.length-me(this,zn,"f").frameLimitInIdealZoom[0]),me(this,zn,"f").autoZoomOutFrameCount>=me(this,zn,"f").autoZoomOutFrameLimit){me(this,zn,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*me(this,zn,"f").autoZoomOutStepRate,me(this,zn,"f").autoZoomOutMinStep);r=Math.max(me(this,zn,"f").minValue,r),r=Math.min(me(this,zn,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}me(this,Xn,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!me(this,Xn,"f").autoZoom&&me(this,Xn,"f").enhancedFocus&&(me(this,zn,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},pe(this,Zn,new es(1e4),"f")}setCameraView(t){if(!(t instanceof ar))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(me(this,Fn,"f")._hideDefaultSelection=!0),me(this,On,"m",qn).call(this)||me(this,Mn,"f").setVideoEl(t.getVideoElement()),pe(this,Fn,t,"f"),this.addListenerToView()}getCameraView(){return me(this,Fn,"f")}releaseCameraView(){me(this,Fn,"f")&&(this.removeListenerFromView(),me(this,Fn,"f").disposed||(me(this,Fn,"f")._singleFrameMode="disabled",me(this,Fn,"f")._onSingleFrameAcquired=null,me(this,Fn,"f")._hideDefaultSelection=!1),me(this,Mn,"f").releaseVideoEl(),pe(this,Fn,null,"f"))}addListenerToView(){if(!me(this,Fn,"f"))return;if(me(this,Fn,"f").disposed)throw new Error("'cameraView' has been disposed.");const t=me(this,Fn,"f");me(this,On,"m",qn).call(this)||this.videoSrc||(t._innerComponent&&(me(this,Mn,"f").tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!me(this,Fn,"f")||me(this,Fn,"f").disposed)return;const t=me(this,Fn,"f");me(this,Mn,"f").tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return me(this,On,"m",qn).call(this)?me(this,Pn,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(me(this,Mn,"f").state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=me(this,Fn,"f");if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,me(this,On,"m",qn).call(this)?t._clickIptSingleFrameMode():(me(this,Mn,"f").setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(me(this,On,"m",qn).call(this));else{try{await me(this,Mn,"f").open()}catch(e){throw t&&t._stopLoading(),e}me(this,Bn,"f")&&this.turnOnTorch().catch((()=>{}));const i=this.getResolution();e.width=i.width,e.height=i.height,e.deviceId=this.getSelectedCamera().deviceId}return pe(this,Pn,"open","f"),t&&(t._innerComponent.style.display="",me(this,On,"m",qn).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),me(this,Mn,"f")._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),me(this,kn,"f").fire("opened",null,{target:this,async:!1}),e}close(){const t=me(this,Fn,"f");if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");this.stopFetching(),this.clearBuffer(),me(this,On,"m",qn).call(this)||me(this,Mn,"f").close(),pe(this,Pn,"closed","f"),me(this,Zn,"f").stopCharging(),t&&(t._innerComponent.style.display="none",me(this,On,"m",qn).call(this)&&t._innerComponent.removeElement("content"),t._stopLoading()),me(this,kn,"f").fire("closed",null,{target:this,async:!1})}pause(){if(me(this,On,"m",qn).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");me(this,Mn,"f").pause()}isPaused(){var t;return!me(this,On,"m",qn).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(me(this,On,"m",qn).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await me(this,Mn,"f").resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await me(this,Mn,"f").setCamera(e),pe(this,Bn,!1,"f");const i=this.getResolution(),r=me(this,Fn,"f");return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),me(this,Mn,"f")._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return me(this,Mn,"f").getCamera()}async getAllCameras(){return me(this,Mn,"f").getCameras()}async setResolution(t){await me(this,Mn,"f").setResolution(t.width,t.height),me(this,Bn,"f")&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=me(this,Fn,"f");return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return me(this,Mn,"f").getResolution()}getAvailableResolutions(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?me(this,kn,"f").on(t,e):me(this,Mn,"f").on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?me(this,kn,"f").off(t,e):me(this,Mn,"f").off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=me(this,Mn,"f"))||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return me(this,Mn,"f").getCameraSettings()}async turnOnTorch(){var t;if(me(this,On,"m",qn).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");await(null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.turnOnTorch()),pe(this,Bn,!0,"f")}async turnOffTorch(){var t;if(me(this,On,"m",qn).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.turnOffTorch()),pe(this,Bn,!1,"f")}async setColorTemperature(t){if(me(this,On,"m",qn).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await me(this,Mn,"f").setColorTemperature(t,!0)}getColorTemperature(){return me(this,Mn,"f").getColorTemperature()}async setExposureCompensation(t){var e;if(me(this,On,"m",qn).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=me(this,Mn,"f"))||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e;if(me(this,On,"m",qn).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=me(this,Mn,"f"))||void 0===e?void 0:e.setZoom(t))}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(me(this,On,"m",qn).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(me(this,On,"m",qn).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=me(this,Mn,"f"))||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(me(this,On,"m",qn).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=me(this,Mn,"f"))||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=me(this,Mn,"f"))||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){me(this,zn,"f").minValue=t.min,me(this,zn,"f").maxValue=t.max}getAutoZoomRange(){return{min:me(this,zn,"f").minValue,max:me(this,zn,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=rt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==ht.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&xe.EF_ENHANCED_FOCUS&&(me(this,Xn,"f").enhancedFocus=!0),t&xe.EF_AUTO_ZOOM&&(me(this,Xn,"f").autoZoom=!0),t&xe.EF_TAP_TO_FOCUS&&(me(this,Xn,"f").tapToFocus=!0,me(this,Mn,"f").enableTapToFocus())}disableEnhancedFeatures(t){t&xe.EF_ENHANCED_FOCUS&&(me(this,Xn,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&xe.EF_AUTO_ZOOM&&(me(this,Xn,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&xe.EF_TAP_TO_FOCUS&&(me(this,Xn,"f").tapToFocus=!1,me(this,Mn,"f").disableTapToFocus()),me(this,On,"m",Qn).call(this)&&me(this,On,"m",Jn).call(this)||me(this,Zn,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!Ve(t)&&!ze(t))throw TypeError("Invalid 'region'.");pe(this,Vn,t?JSON.parse(JSON.stringify(t)):null,"f"),me(this,Fn,"f")&&!me(this,Fn,"f").disposed&&me(this,Fn,"f").setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),me(this,Fn,"f")&&!me(this,Fn,"f").disposed&&(null===t?me(this,Fn,"f").setScanRegionMaskVisible(!1):me(this,Fn,"f").setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(me(this,Vn,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");pe(this,Gn,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!me(this,Mn,"f").isVideoLoaded()||me(this,On,"m",qn).call(this))}startFetching(){if(me(this,On,"m",qn).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");me(this,Yn,"f")||(pe(this,Yn,!0,"f"),me(this,On,"m",$n).call(this))}stopFetching(){me(this,Yn,"f")&&(ss._onLog&&ss._onLog("DCE: stop fetching loop: "+Date.now()),me(this,Hn,"f")&&clearTimeout(me(this,Hn,"f")),pe(this,Yn,!1,"f"))}fetchImage(){if(me(this,On,"m",qn).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Ke.convert(me(this,Vn,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=me(this,Mn,"f").getFrameData({position:i,pixelFormat:is.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===yr.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:rs.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:gt.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:me(this,jn,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,me(this,Yn,"f")&&(me(this,Hn,"f")&&clearTimeout(me(this,Hn,"f")),pe(this,Hn,setTimeout((()=>{this.disposed||me(this,On,"m",$n).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){pe(this,Wn,t,"f")}getPixelFormat(){return me(this,Wn,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(me(this,On,"m",qn).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=Ke.convert(me(this,Vn,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=me(this,Un,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=me(this,On,"m",ts).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=me(this,On,"m",ts).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),me(this,Mn,"f").dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function os(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function as(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}Dn=ss,Mn=new WeakMap,Fn=new WeakMap,Pn=new WeakMap,kn=new WeakMap,Bn=new WeakMap,Nn=new WeakMap,Un=new WeakMap,jn=new WeakMap,Gn=new WeakMap,Vn=new WeakMap,Wn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,Zn=new WeakMap,Kn=new WeakMap,On=new WeakSet,qn=function(){return"disabled"!==this.singleFrameMode},Jn=function(){return!this.videoSrc&&"opened"===me(this,Mn,"f").state},Qn=function(){for(let t in me(this,Xn,"f"))if(1==me(this,Xn,"f")[t])return!0;return!1},$n=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!me(this,Yn,"f"))return me(this,Hn,"f")&&clearTimeout(me(this,Hn,"f")),void pe(this,Hn,setTimeout((()=>{this.disposed||me(this,On,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;ss._onLog&&ss._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=me(this,Gn,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=me(this,Gn,"f"))||void 0===t||t.onErrorReceived(ut.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),ss._onLog&&ss._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),me(this,kn,"f").fire("frameAddedToBuffer",null,{async:!1})):ss._onLog&&ss._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case r.BOPM_BLOCK:break;case r.BOPM_UPDATE:e()}else e();me(this,Hn,"f")&&clearTimeout(me(this,Hn,"f")),pe(this,Hn,setTimeout((()=>{this.disposed||me(this,On,"m",t).call(this)}),this.fetchInterval),"f")},ts=function(t){if(!me(this,Fn,"f"))throw new Error("Camera view is not set.");if(me(this,Fn,"f").disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!me(this,On,"m",qn).call(this)&&!me(this,Mn,"f").isVideoLoaded())throw new Error("Video is not loaded.");if(me(this,On,"m",qn).call(this)&&!me(this,Fn,"f")._cvsSingleFrameMode)throw new Error("No image is selected.");const e=me(this,Fn,"f")._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=me(this,Fn,"f")._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(me(this,On,"m",qn).call(this)){const t=me(this,Fn,"f")._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=me(this,Fn,"f").getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return hs.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return hs.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return hs.multiply(t,[e,0,0,0,i,0,0,0,1])}}var ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Es,Cs,Ts,bs,Ss,Is,xs,As,Rs,Os,Ds;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ls||(ls={}));class Ls{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(as(Ls,cs,!1,"f",us),!1):(as(Ls,cs,!0,"f",us),!0)}get disposed(){return os(this,_s,"f")}constructor(){ds.set(this,ls.RGBA),fs.set(this,null),gs.set(this,null),ms.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,ps.set(this,null),_s.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==os(Ls,cs,"f",us)&&Ls.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!os(Ls,cs,"f",us))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Ls._onLog&&(o=Date.now(),Ls._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=ls.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!os(Ls,cs,"f",us)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Ls._onLog&&Ls._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);as(this,gs,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),as(this,ms,e(t),"f"),as(this,fs,i(t),"f"),as(this,ds,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[ls.GREY,ls.GREY32].includes(p)?1:0);let m,_,v=hs.translate(hs.identity(),-1,-1);v=hs.scale(v,2,2),v=hs.scale(v,1/t.canvas.width,1/t.canvas.height),m=hs.translate(v,u,d),m=hs.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=hs.translate(hs.identity(),a/i,h/r),_=hs.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,os(this,fs,"f"),e),v(t,os(this,gs,"f"),os(this,ms,"f"),os(this,fs,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Ls._onLog&&Ls._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Ls._onLog&&Ls._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===ls.GREY?ls.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Ls._onLog&&Ls._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Ls._onLog&&(n=Date.now(),Ls._onLog("transformPixelFormat(), START: "+n)),e===i)return Ls._onLog&&Ls._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[ls.RGBA,ls.RBGA,ls.GRBA,ls.GBRA,ls.BRGA,ls.BGRA];if(o.includes(e))if(i===ls.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Ls._onLog&&(s=Date.now(),Ls._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=ls.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),os(Ls,cs,"f",us)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Ls._onLog&&Ls._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===ls.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(me(this,Cs,"f")||pe(this,Cs,new Ms,"f"),!me(this,Cs,"f").magnifierCanvas)return;document.body.contains(me(this,Cs,"f").magnifierCanvas)||(me(this,Cs,"f").magnifierCanvas.style.position="fixed",me(this,Cs,"f").magnifierCanvas.style.boxSizing="content-box",me(this,Cs,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(me(this,Cs,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void me(this,bs,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];me(this,Cs,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(me(this,Cs,"f").magnifierCanvas.style.left="auto",me(this,Cs,"f").magnifierCanvas.style.top="0",me(this,Cs,"f").magnifierCanvas.style.right="0"):(me(this,Cs,"f").magnifierCanvas.style.left="0",me(this,Cs,"f").magnifierCanvas.style.top="0",me(this,Cs,"f").magnifierCanvas.style.right="auto")}me(this,Cs,"f").show()})),bs.set(this,(()=>{me(this,Cs,"f")&&me(this,Cs,"f").hide()})),Ss.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if(e="string"==typeof t?await ii(t):t,e instanceof HTMLDivElement&&0==e.childElementCount){const t=me(this,ws,"m",Is).call(this);this._setUIElement(t),e.append(this.getUIElement()),this.UIElement=e}else this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new sr,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(Ge(t)){pe(this,Es,t,"f");const{width:e,height:i,bytes:r,format:n}=Object.assign({},t);let o;if(n===s.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{me(this,xs,"f",Ds).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,me(this,xs,"f",Ds).delete(t),me(this,xs,"f",Os).add(t)}))}else me(this,xs,"f",Rs)||(pe(this,xs,!0,"f",Rs),console.warn("The requested audio tracks exceed 64 and will not be played."));t&&me(this,xs,"f",Ds).add(t)}static vibrate(){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ps.vibrateDuration)}}xs=Ps,As={value:"data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"},Rs={value:!1},Os={value:new Set},Ds={value:new Set},Ps.beepSoundSource=me(Ps,xs,"f",As),Ps.vibrateDuration=300;var ks=Object.freeze({__proto__:null,CameraEnhancer:ss,CameraEnhancerModule:class{static getVersion(){return"4.0.3"}},CameraView:ar,DrawingStyleManager:tr,get EnumDrawingItemMediaType(){return Se},get EnumDrawingItemState(){return Ie},get EnumEnhancedFeatures(){return xe},Feedback:Ps,ImageDrawingItem:class extends Ne{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return me(this,oi,"f")}constructor(t,e,i,r){if(super(null,r),si.set(this,void 0),oi.set(this,void 0),!ze(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new Re.Image(t,{left:e.x,top:e.y}));else{if(!Ge(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;if(i.width=t.width,i.height=t.height,t.format===s.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new Re.Control({positionHandler:li,actionHandler:di(i>0?i-1:r,ui),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=Re.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){me(this,pi,"f")&&this.setLine(me(this,pi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!We(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else pe(this,pi,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return me(this,pi,"f")?JSON.parse(JSON.stringify(me(this,pi,"f"))):null}},QuadDrawingItem:Qi,RectDrawingItem:hi,TextDrawingItem:mi});const Bs="undefined"==typeof self,Ns=(()=>{if(!Bs&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Us=t=>{if(null==t&&(t="./"),Bs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};null==nt.dbr&&(nt.dbr=Ns),ot.dbr={js:!1,wasm:!0,deps:["license","dip"]},rt.dbr={};const js="1.2.0";"string"!=typeof nt.std&&w(nt.std.version,js)<0&&(nt.std={version:js,path:Us(Ns+`../../dynamsoft-capture-vision-std@${js}/dist/`)});const Gs="2.2.10";(!nt.dip||"string"!=typeof nt.dip&&w(nt.dip.version,Gs)<0)&&(nt.dip={version:Gs,path:Us(Ns+`../../dynamsoft-image-processing@${Gs}/dist/`)});const Vs="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};var Ws,Ys,Hs,Xs;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(Ws||(Ws={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Ys||(Ys={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(Hs||(Hs={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}(Xs||(Xs={}));var zs=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=it.dbr&&it.dbr.wasm;return`10.2.10(Worker: ${it.dbr&&it.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:Vs,get EnumDeblurMode(){return Xs},get EnumExtendedBarcodeResultType(){return Ws},get EnumLocalizationMode(){return Hs},get EnumQRCodeErrorCorrectionLevel(){return Ys}});const Zs=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await qs(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),Ks=t=>{const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},qs=async(t,e)=>{const i=Ks(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},Js=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===s.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===s.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const $s="undefined"==typeof self,to=(()=>{if(!$s&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),eo=t=>{if(null==t&&(t="./"),$s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};null==nt.utility&&(nt.utility=to),ot.utility={js:!0,wasm:!0};const io="1.2.10";"string"!=typeof nt.std&&w(nt.std.version,io)<0&&(nt.std={version:io,path:eo(to+`../../dynamsoft-capture-vision-std@${io}/dist/`)});const ro="2.2.30";(!nt.dip||"string"!=typeof nt.dip&&w(nt.dip.version,ro)<0)&&(nt.dip={version:ro,path:eo(to+`../../dynamsoft-image-processing@${ro}/dist/`)});const no={barcode:2,text_line:4,detected_quad:8,normalized_image:16},so=t=>Object.values(no).includes(t)||no.hasOwnProperty(t),oo=(t,e)=>"string"==typeof t?e[no[t]]:e[t],ao=(t,e,i)=>{"string"==typeof t?e[no[t]]=i:e[t]=i};var ho=Object.freeze({__proto__:null,ImageManager:class{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const r=Js(t);return Zs(r,e,i)}async drawOnImage(t,e,i,r=4294901760,n=1,s){let o;if(t instanceof Blob)o=await Qs(t);else if("string"==typeof t){let e=await y(t,"blob");o=await Qs(e)}return await new Promise(((t,a)=>{let h=q();J[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Z.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}},MultiFrameResultCrossFilter:class{constructor(){this.verificationEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!0,[lt.CRIT_DETECTED_QUAD]:!0,[lt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!1,[lt.CRIT_DETECTED_QUAD]:!1,[lt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[lt.CRIT_BARCODE]:3e3,[lt.CRIT_TEXT_LINE]:3e3,[lt.CRIT_DETECTED_QUAD]:3e3,[lt.CRIT_NORMALIZED_IMAGE]:3e3}}enableResultCrossVerification(t,e){so(t)&&ao(t,this.verificationEnabled,e)}isResultCrossVerificationEnabled(t){return!!so(t)&&oo(t,this.verificationEnabled)}enableResultDeduplication(t,e){so(t)&&ao(t,this.duplicateFilterEnabled,e)}isResultDeduplicationEnabled(t){return!!so(t)&&oo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){so(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),ao(t,this.duplicateForgetTime,e))}getDuplicateForgetTime(t){return so(t)?oo(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[lt.CRIT_BARCODE,lt.CRIT_TEXT_LINE,lt.CRIT_DETECTED_QUAD];for(let i=0;i{const i=Ks(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r}});t.CVR=ae,t.Core=wt,t.DBR=zs,t.DCE=ks,t.License=Yt,t.Utility=ho})); diff --git a/dist/dbr.bundle.mjs b/dist/dbr.bundle.mjs new file mode 100644 index 00000000..1a5a0fb8 --- /dev/null +++ b/dist/dbr.bundle.mjs @@ -0,0 +1,11 @@ +/*! +* Dynamsoft JavaScript Library +* @product Dynamsoft Barcode Reader JS Edition Bundle +* @website http://www.dynamsoft.com +* @copyright Copyright 2024, Dynamsoft Corporation +* @author Dynamsoft +* @version 10.2.1000 +* @fileoverview Dynamsoft JavaScript Library for Barcode Reader +* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ +*/ +function t(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function e(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}var i,r,n;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(i||(i={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(r||(r={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(n||(n={}));const s=t=>Object.prototype.toString.call(t),o=t=>Array.isArray?Array.isArray(t):"[object Array]"===s(t),a=t=>"[object Boolean]"===s(t),h=t=>"number"==typeof t&&!Number.isNaN(t),l=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),c=t=>!(!l(t)||!h(t.x)||!h(t.y)||!h(t.radius)||t.radius<0||!h(t.startAngle)||!h(t.endAngle)),u=t=>!!l(t)&&!!o(t.points)&&0!=t.points.length&&!t.points.some((t=>!p(t))),d=t=>!(!l(t)||!(t.bytes instanceof Uint8Array)||!h(t.width)||t.width<=0||!h(t.height)||t.height<=0||!h(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!g(t.tag)),f=t=>!(!l(t)||!h(t.left)||t.left<0||!h(t.top)||t.top<0||!h(t.right)||t.right<0||!h(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!a(t.isMeasuredInPercentage)),g=t=>!!l(t)&&!!h(t.imageId)&&"type"in t,m=t=>!(!l(t)||!p(t.startPoint)||!p(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),p=t=>!!l(t)&&!!h(t.x)&&!!h(t.y),_=t=>!!l(t)&&!!o(t.points)&&0!=t.points.length&&!t.points.some((t=>!p(t))),v=t=>!!l(t)&&!!o(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!p(t))),y=t=>!(!l(t)||!h(t.x)||!h(t.y)||!h(t.width)||t.width<0||!h(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!a(t.isMeasuredInPercentage));async function w(t,e){return await new Promise(((i,r)=>{let n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType=e,n.send(),n.onloadend=async()=>{n.status<200||n.status>=300?r(t+" "+n.status):i(n.response)},n.onerror=()=>{r(new Error("Network Error: "+n.statusText))}}))}function E(t){return/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t)}const C=(t,e)=>{let i=t.split("."),r=e.split(".");for(let t=0;t=t(this,I,"f"))switch(t(this,x,"f")){case i.BOPM_BLOCK:break;case i.BOPM_UPDATE:if(t(this,S,"f").push(e),l(t(this,R,"f"))&&h(t(this,R,"f").imageId)&&1==t(this,R,"f").keepInBuffer)for(;t(this,S,"f").length>t(this,I,"f");){const e=t(this,S,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)!==t(this,R,"f").imageId}));t(this,S,"f").splice(e,1)}else t(this,S,"f").splice(0,t(this,S,"f").length-t(this,I,"f"))}else t(this,S,"f").push(e)}getImage(){if(0===t(this,S,"f").length)return null;let e;if(t(this,R,"f")&&h(t(this,R,"f").imageId)){const i=t(this,b,"m",D).call(this,t(this,R,"f").imageId);if(i<0)throw new Error(`Image with id ${t(this,R,"f").imageId} doesn't exist.`);e=t(this,S,"f").slice(i,i+1)[0]}else e=t(this,S,"f").pop();if([n.IPF_RGB_565,n.IPF_RGB_555,n.IPF_RGB_888,n.IPF_ARGB_8888,n.IPF_RGB_161616,n.IPF_ARGB_16161616,n.IPF_ABGR_8888,n.IPF_ABGR_16161616,n.IPF_BGR_888].includes(e.format)){if(t(this,O,"f")===r.CCUT_RGB_R_CHANNEL_ONLY){s._onLog&&s._onLog("only get R channel data.");const t=new Uint8Array(e.width*e.height);for(let i=0;i0!==t.length&&t.every((t=>h(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==i&&!a(i))throw new TypeError("Invalid 'keepInBuffer'.");e(this,R,{imageId:t,keepInBuffer:i},"f")}_resetNextReturnedImage(){e(this,R,null,"f")}hasImage(e){return t(this,b,"m",D).call(this,e)>=0}startFetching(){e(this,A,!0,"f")}stopFetching(){e(this,A,!1,"f")}setMaxImageCount(i){if("number"!=typeof i)throw new TypeError("Invalid 'count'.");if(i<1||Math.round(i)!==i)throw new Error("Invalid 'count'.");for(e(this,I,i,"f");t(this,S,"f")&&t(this,S,"f").length>i;)t(this,S,"f").shift()}getMaxImageCount(){return t(this,I,"f")}getImageCount(){return t(this,S,"f").length}clearBuffer(){t(this,S,"f").length=0}isBufferEmpty(){return 0===t(this,S,"f").length}setBufferOverflowProtectionMode(t){e(this,x,t,"f")}getBufferOverflowProtectionMode(){return t(this,x,"f")}setColourChannelUsageType(t){e(this,O,t,"f")}getColourChannelUsageType(){return t(this,O,"f")}};S=new WeakMap,I=new WeakMap,x=new WeakMap,A=new WeakMap,R=new WeakMap,O=new WeakMap,b=new WeakSet,D=function(e){if("number"!=typeof e)throw new TypeError("Invalid 'imageId'.");return t(this,S,"f").findIndex((t=>{var i;return(null===(i=t.tag)||void 0===i?void 0:i.imageId)===e}))};const M="undefined"==typeof self,F=(()=>{if(!M&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),P=t=>{if(null==t&&(t="./"),M);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};let k,B,N,U,j;"undefined"!=typeof navigator&&(k=navigator,B=k.userAgent,N=k.platform,U=k.mediaDevices),function(){if(!M){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:k.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:N,search:"Win"},Mac:{str:N},Linux:{str:N}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||B,o=n.search||e,a=n.verStr||B,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||B,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=B.indexOf("Windows NT")&&(n="HarmonyOS"),j={browser:i,version:r,OS:n}}M&&(j={browser:"ssr",version:0,OS:"ssr"})}();const G="undefined"!=typeof WebAssembly&&B&&!(/Safari/.test(B)&&!/Chrome/.test(B)&&/\(.+\s11_2_([2-6]).*\)/.test(B)),W=!("undefined"==typeof Worker),V=!(!U||!U.getUserMedia),Y=async()=>{let t=!1;if(V)try{(await U.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===j.browser&&j.version>66||"Safari"===j.browser&&j.version>13||"OPR"===j.browser&&j.version>43||"Edge"===j.browser&&j.version;const H=t=>t&&"object"==typeof t&&"function"==typeof t.then;let X=class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(H(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,H(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}};const z={},Z=t=>{let e=z[t],i=!1;return e?e.isEmpty?e.task=()=>{}:i=!0:e=z[t]=new X((()=>{})),{p:e,justWait:i}},K=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(z[t]=z[t]||new X);await Promise.all(i)},q=async(t,e)=>{let i,r="string"==typeof t?[t]:t,n=[];for(let t of r){let r;n.push(r=z[t]=z[t]||new X(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(n)};let J,Q=0;const $=()=>Q++,tt={};let et;const it=t=>{et=t,J&&J.postMessage({type:"setBLog",body:{value:!!t}})};let rt=!1;const nt=t=>{rt=t,J&&J.postMessage({type:"setBDebug",body:{value:!!t}})},st={},ot={},at={std:{version:"1.2.10",path:P(F+"../../dynamsoft-capture-vision-std@1.2.10/dist/")},core:{version:"3.2.30",path:F}},ht=new Proxy(at,{get(t,e,i){let r=Reflect.get(t,e,i);return r&&r.path&&(r=r.path),r}}),lt={dip:{wasm:!0}},ct=async t=>{let e;t instanceof Array||(t=t?[t]:[]);{let t=z.core;e=!t||t.isEmpty}let i=new Map;for(let e of t){if(e=e.toLowerCase(),"std"==e||"core"==e)continue;if(!lt[e])throw Error("The '"+e+"' module cannot be found.");let t=lt[e].deps;if(null==t?void 0:t.length)for(let e of t){let t=z[e];i.has(e)||i.set(e,!t||t.isEmpty)}let r=z[e];i.has(e)||i.set(e,!r||r.isEmpty)}let r=[];e&&r.push("core"),r.push(...i.keys()),await q(r,(async()=>{const t=[...i.entries()].filter((t=>t[1])).map((t=>t[0])),r={};for(let t in ht){if("rootDirectory"==t)continue;let e=ht[t];ht.rootDirectory&&(e.startsWith("http://")||e.startsWith("https://")||(e=ht.rootDirectory+"/"+e)),r[t]=P(e)}const n={};for(let e of t)n[e]=lt[e];const s={engineResourcePaths:r,autoResources:n,names:t};let o=new X;if(e){s.needLoadCore=!0;let t=r.core+ut._workerName;r.rootDirectory&&(t=r.rootDirectory+t),t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),J=new Worker(t),J.onerror=t=>{let e=new Error(t.message);o.reject(e)},J.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,r=e.id,n=e.body;switch(i){case"log":et&&et(e.message);break;case"task":try{tt[r](n),delete tt[r]}catch(t){throw delete tt[r],t}break;case"event":try{tt[r](n)}catch(t){throw t}break;default:console.log(t)}})),s.bLog=!!et,s.bd=rt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await K("worker");let a=Q++;tt[a]=t=>{if(t.success)Object.assign(st,t.versions),"{}"!==JSON.stringify(t.versions)&&(ut._versions=t.versions),o.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),o.reject(e)}},J.postMessage({type:"loadWasm",body:s,id:a}),e&&q("worker",(()=>Promise.resolve())),await o}))};class ut{static get engineResourcePaths(){return ht}static set engineResourcePaths(t){Object.assign(at,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return et}static set _onLog(t){it(t)}static get _bDebug(){return rt}static set _bDebug(t){nt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!z[t]&&z[t].isFulfilled}static async loadWasm(t){return await ct(t)}static async detectEnvironment(){return await(async()=>({wasm:G,worker:W,getUserMedia:V,camera:await Y(),browser:j.browser,version:j.version,OS:j.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=$();tt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},J.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.2.30(Worker: ${st.core&&st.core.worker||"Not Loaded"}, Wasm: ${st.core&&st.core.wasm||"Not Loaded"})`}static enableLogging(){L._onLog=console.log,ut._onLog=console.log}static disableLogging(){L._onLog=null,ut._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cfd",id:r,body:{count:t}})}))}}var dt,ft,gt,mt,pt,_t,vt,yt,wt,Et,Ct;ut._bSupportDce4Module=-1,ut._bSupportIRTModule=-1,ut._versions=null,ut._workerName="core.worker.js",ut.browserInfo=j,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(dt||(dt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(ft||(ft={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID"}(gt||(gt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(mt||(mt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(pt||(pt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(_t||(_t={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(vt||(vt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(yt||(yt={})),function(t){t[t.IRUT_NULL=0]="IRUT_NULL",t[t.IRUT_COLOUR_IMAGE=1]="IRUT_COLOUR_IMAGE",t[t.IRUT_SCALED_DOWN_COLOUR_IMAGE=2]="IRUT_SCALED_DOWN_COLOUR_IMAGE",t[t.IRUT_GRAYSCALE_IMAGE=4]="IRUT_GRAYSCALE_IMAGE",t[t.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE=8]="IRUT_TRANSOFORMED_GRAYSCALE_IMAGE",t[t.IRUT_ENHANCED_GRAYSCALE_IMAGE=16]="IRUT_ENHANCED_GRAYSCALE_IMAGE",t[t.IRUT_PREDETECTED_REGIONS=32]="IRUT_PREDETECTED_REGIONS",t[t.IRUT_BINARY_IMAGE=64]="IRUT_BINARY_IMAGE",t[t.IRUT_TEXTURE_DETECTION_RESULT=128]="IRUT_TEXTURE_DETECTION_RESULT",t[t.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE=256]="IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE",t[t.IRUT_TEXTURE_REMOVED_BINARY_IMAGE=512]="IRUT_TEXTURE_REMOVED_BINARY_IMAGE",t[t.IRUT_CONTOURS=1024]="IRUT_CONTOURS",t[t.IRUT_LINE_SEGMENTS=2048]="IRUT_LINE_SEGMENTS",t[t.IRUT_TEXT_ZONES=4096]="IRUT_TEXT_ZONES",t[t.IRUT_TEXT_REMOVED_BINARY_IMAGE=8192]="IRUT_TEXT_REMOVED_BINARY_IMAGE",t[t.IRUT_CANDIDATE_BARCODE_ZONES=16384]="IRUT_CANDIDATE_BARCODE_ZONES",t[t.IRUT_LOCALIZED_BARCODES=32768]="IRUT_LOCALIZED_BARCODES",t[t.IRUT_SCALED_UP_BARCODE_IMAGE=65536]="IRUT_SCALED_UP_BARCODE_IMAGE",t[t.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE=131072]="IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE",t[t.IRUT_COMPLEMENTED_BARCODE_IMAGE=262144]="IRUT_COMPLEMENTED_BARCODE_IMAGE",t[t.IRUT_DECODED_BARCODES=524288]="IRUT_DECODED_BARCODES",t[t.IRUT_LONG_LINES=1048576]="IRUT_LONG_LINES",t[t.IRUT_CORNERS=2097152]="IRUT_CORNERS",t[t.IRUT_CANDIDATE_QUAD_EDGES=4194304]="IRUT_CANDIDATE_QUAD_EDGES",t[t.IRUT_DETECTED_QUADS=8388608]="IRUT_DETECTED_QUADS",t[t.IRUT_LOCALIZED_TEXT_LINES=16777216]="IRUT_LOCALIZED_TEXT_LINES",t[t.IRUT_RECOGNIZED_TEXT_LINES=33554432]="IRUT_RECOGNIZED_TEXT_LINES",t[t.IRUT_NORMALIZED_IMAGES=67108864]="IRUT_NORMALIZED_IMAGES",t[t.IRUT_SHORT_LINES=134217728]="IRUT_SHORT_LINES",t[t.IRUT_ALL=268435455]="IRUT_ALL"}(wt||(wt={})),function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(Et||(Et={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(Ct||(Ct={}));let Tt="./";if(document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}Tt=t.substring(0,t.lastIndexOf("/")+1)}const bt=t=>{null==t&&(t="./");let e=document.createElement("a");return e.href=t,(t=e.href).endsWith("/")||(t+="/"),t};ut.engineResourcePaths={std:bt(Tt+"../../dynamsoft-capture-vision-std@1.2.10/dist/"),dip:bt(Tt+"../../dynamsoft-image-processing@2.2.30/dist/"),core:bt(Tt+"../../dynamsoft-core@3.2.30/dist/"),license:bt(Tt+"../../dynamsoft-license@3.2.21/dist/"),cvr:bt(Tt+"../../dynamsoft-capture-vision-router@2.2.30/dist/"),dce:bt(Tt+"../../dynamsoft-camera-enhancer@4.0.3/dist/"),dbr:bt(Tt+"../../dynamsoft-barcode-reader@10.2.10/dist/")};const St="undefined"==typeof self,It=St?{}:self,xt=(()=>{if(!St&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),At=t=>{if(null==t&&(t="./"),St);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},Rt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Ot=class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(Rt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Rt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}};const Dt=" is not allowed to change after `createInstance` or `loadWasm` is called.",Lt=!St&&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"))||"",Mt=(t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`license`"+Dt);i._license=e};!St&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ft=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{const i=t;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Dt);i._licenseServer=Ft(e)},kt=(t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Dt);i._deviceFriendlyName=e||""};let Bt,Nt,Ut,jt,Gt;"undefined"!=typeof navigator&&(Bt=navigator,Nt=Bt.userAgent,Ut=Bt.platform,jt=Bt.mediaDevices),function(){if(!St){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Bt.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Ut,search:"Win"},Mac:{str:Ut},Linux:{str:Ut}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||Nt,o=n.search||e,a=n.verStr||Nt,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||Nt,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=Nt.indexOf("Windows NT")&&(n="HarmonyOS"),Gt={browser:i,version:r,OS:n}}St&&(Gt={browser:"ssr",version:0,OS:"ssr"})}(),jt&&jt.getUserMedia,"Chrome"===Gt.browser&&Gt.version>66||"Safari"===Gt.browser&&Gt.version>13||"OPR"===Gt.browser&&Gt.version>43||"Edge"===Gt.browser&&Gt.version;const Wt=async()=>(ct("license"),q("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:r,rmk:n,cv:s}=((t,e=!1)=>{const i=Yt;if(i._pLoad.isEmpty){let r,n,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Ft(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),r=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(It.crypto||(s="Please upgrade your browser to support online key."),It.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==l)throw new Error(s);l=0,console.warn(s),i._lastErrorCode=-1,i._lastErrorString=s}return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:r,cv:n}}throw new Error("Can't preprocess license again"+Dt)})(),o=new Ot;Yt._pLoad.task=o,(async()=>{try{await Yt._pLoad}catch(t){}})();let a=$();tt[a]=e=>{if(e.message&&Yt._onAuthMessage){let t=Yt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,r=!1;if(1===t&&(r=!0),e.success?(et&&et("init license success"),e.message&&console.warn(e.message),ut._bSupportIRTModule=e.bSupportIRTModule,ut._bSupportDce4Module=e.bSupportDce4Module,Yt.bPassValidation=!0):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),r||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(r=!0)),r){let t=at.license;at.rootDirectory&&(t=at.rootDirectory+"/"+t),t=At(t),(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.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 t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Yt._bNeverShowDialog,engineResourcePath:t,_onLog:et},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await K("worker"),J.postMessage({type:"dynamsoft",body:{v:"3.2.21",brtk:!!t,bptk:1===t,l:e,os:Gt,fn:Yt.deviceFriendlyName,ls:i,sp:r,rmk:n,cv:s},id:a}),Yt.bCallInitLicense=!0,await o})));let Vt;ot.license={},ot.license.dynamsoft=Wt,ot.license.getAR=async()=>{{let t=z.dynamsoft_inited;t&&t.isRejected&&await t}return J?new Promise(((t,e)=>{let i=$();tt[i]=async i=>{if(i.success){delete i.success;{let t=Yt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},J.postMessage({type:"getAR",id:i})})):null};let Yt=class t{static setLicenseServer(e){Pt(t,e)}static get license(){return this._license}static set license(e){Mt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Pt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){kt(t,e)}static initLicense(e,i){if(Mt(t,e),t.bCallInitLicense=!0,i)return Wt()}static setDeviceFriendlyName(e){kt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await q("dynamsoft_uuid",(async()=>{await ct();let t=new Ot,e=$();tt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},J.postMessage({type:"getDeviceUUID",id:e}),Vt=await t})),Vt))()}};Yt._pLoad=new Ot,Yt.bPassValidation=!1,Yt.bCallInitLicense=!1,Yt._license=Lt,Yt._licenseServer=[],Yt._deviceFriendlyName="",null==at.license&&(at.license=xt),lt.license={wasm:!0},ot.license.LicenseManager=Yt;const Ht="1.2.10";"string"!=typeof at.std&&C(at.std.version,Ht)<0&&(at.std={version:Ht,path:At(xt+`../../dynamsoft-capture-vision-std@${Ht}/dist/`)});let Xt=class{static getVersion(){return`3.2.21(Worker: ${st.license&&st.license.worker||"Not Loaded"}, Wasm: ${st.license&&st.license.wasm||"Not Loaded"})`}};const zt=t=>t&&"object"==typeof t&&"function"==typeof t.then;let Zt=class extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(zt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,zt(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}};class Kt{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=$();tt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},J.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_setMaxBufferedItems",id:r,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=$();tt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},J.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var qt={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1};const Jt=(t,e)=>{for(let t in e._irrRegistryState)e._irrRegistryState[t]=!1;for(let i of t._intermediateResultReceiverSet)if(i.isDce)e._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let t in i)e._irrRegistryState[t]||(e._irrRegistryState[t]=!!i[t])};let Qt=class{constructor(t){this._irrRegistryState=qt,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._cvr._intermediateResultReceiverSet.add(t),Jt(this._cvr,this);let e=-1,i={};if(!t.isDce){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,r)=>{let n=$();tt[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},J.postMessage({type:"cvr_setIrrRegistry",id:n,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:String(e),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._cvr._intermediateResultReceiverSet.delete(t),Jt(this._cvr,this),await new Promise(((t,e)=>{let i=$();tt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},J.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}};const $t="undefined"==typeof self,te=(()=>{if(!$t&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),ee=t=>{if(null==t&&(t="./"),$t);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ie;null==at.cvr&&(at.cvr=te),lt.cvr={js:!0,wasm:!0,deps:["license","dip"]},ot.cvr={};const re="1.2.10";"string"!=typeof at.std&&C(at.std.version,re)<0&&(at.std={version:re,path:ee(te+`../../dynamsoft-capture-vision-std@${re}/dist/`)});const ne="2.2.30";(!at.dip||"string"!=typeof at.dip&&C(at.dip.version,ne)<0)&&(at.dip={version:ne,path:ee(te+`../../dynamsoft-image-processing@${ne}/dist/`)});let se=class{static getVersion(){return this._version}};var oe,ae;function he(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;he(t.referencedItem,e)}}se._version=`2.2.30(Worker: ${null===(ie=st.cvr)||void 0===ie?void 0:ie.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(oe||(oe={})),function(t){t[t.IRUT_NULL=0]="IRUT_NULL",t[t.IRUT_COLOUR_IMAGE=1]="IRUT_COLOUR_IMAGE",t[t.IRUT_SCALED_DOWN_COLOUR_IMAGE=2]="IRUT_SCALED_DOWN_COLOUR_IMAGE",t[t.IRUT_GRAYSCALE_IMAGE=4]="IRUT_GRAYSCALE_IMAGE",t[t.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE=8]="IRUT_TRANSOFORMED_GRAYSCALE_IMAGE",t[t.IRUT_ENHANCED_GRAYSCALE_IMAGE=16]="IRUT_ENHANCED_GRAYSCALE_IMAGE",t[t.IRUT_PREDETECTED_REGIONS=32]="IRUT_PREDETECTED_REGIONS",t[t.IRUT_BINARY_IMAGE=64]="IRUT_BINARY_IMAGE",t[t.IRUT_TEXTURE_DETECTION_RESULT=128]="IRUT_TEXTURE_DETECTION_RESULT",t[t.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE=256]="IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE",t[t.IRUT_TEXTURE_REMOVED_BINARY_IMAGE=512]="IRUT_TEXTURE_REMOVED_BINARY_IMAGE",t[t.IRUT_CONTOURS=1024]="IRUT_CONTOURS",t[t.IRUT_LINE_SEGMENTS=2048]="IRUT_LINE_SEGMENTS",t[t.IRUT_TEXT_ZONES=4096]="IRUT_TEXT_ZONES",t[t.IRUT_TEXT_REMOVED_BINARY_IMAGE=8192]="IRUT_TEXT_REMOVED_BINARY_IMAGE",t[t.IRUT_CANDIDATE_BARCODE_ZONES=16384]="IRUT_CANDIDATE_BARCODE_ZONES",t[t.IRUT_LOCALIZED_BARCODES=32768]="IRUT_LOCALIZED_BARCODES",t[t.IRUT_SCALED_UP_BARCODE_IMAGE=65536]="IRUT_SCALED_UP_BARCODE_IMAGE",t[t.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE=131072]="IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE",t[t.IRUT_COMPLEMENTED_BARCODE_IMAGE=262144]="IRUT_COMPLEMENTED_BARCODE_IMAGE",t[t.IRUT_DECODED_BARCODES=524288]="IRUT_DECODED_BARCODES",t[t.IRUT_LONG_LINES=1048576]="IRUT_LONG_LINES",t[t.IRUT_CORNERS=2097152]="IRUT_CORNERS",t[t.IRUT_CANDIDATE_QUAD_EDGES=4194304]="IRUT_CANDIDATE_QUAD_EDGES",t[t.IRUT_DETECTED_QUADS=8388608]="IRUT_DETECTED_QUADS",t[t.IRUT_LOCALIZED_TEXT_LINES=16777216]="IRUT_LOCALIZED_TEXT_LINES",t[t.IRUT_RECOGNIZED_TEXT_LINES=33554432]="IRUT_RECOGNIZED_TEXT_LINES",t[t.IRUT_NORMALIZED_IMAGES=67108864]="IRUT_NORMALIZED_IMAGES",t[t.IRUT_SHORT_LINES=134217728]="IRUT_SHORT_LINES",t[t.IRUT_ALL=134217727]="IRUT_ALL"}(ae||(ae={}));let le=class t{constructor(){this.maxCvsSideLength=["iPhone","Android","HarmonyOS"].includes(ut.browserInfo.OS)?2048:4096,this._isa=null,this._dsImage=null,this._instanceID=void 0,this._bPauseScan=!0,this._bNeedOutputOriginalImage=!1,this._canvas=null,this._resultReceiverSet=new Set,this._isaStateListenerSet=new Set,this._resultFilterSet=new Set,this._intermediateResultReceiverSet=new Set,this._intermediateResultManager=null,this._bufferdItemsManager=null,this._bOpenDetectVerify=!1,this._bOpenNormalizeVerify=!1,this._bOpenBarcodeVerify=!1,this._bOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._compressRate=0,this._dynamsoft=!1,this.captureInParallel=!0,this.bDestroyed=!1,this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this),this._promiseStartScan=null}get disposed(){return this.bDestroyed}static async createInstance(){if(!ot.license)throw Error("Module `license` is not existed.");await ot.license.dynamsoft(),await ct(["cvr"]);const e=new t,i=new Zt;let r=$();return tt[r]=async t=>{var r;if(t.success)e._instanceID=t.instanceID,e._currentSettings=JSON.parse(t.outputSettings),se._version=`2.2.30(Worker: ${null===(r=st.cvr)||void 0===r?void 0:r.worker}, Wasm: ${t.version})`,0===ut.bSupportDce4Module&&(e._intermediateResultManager=e.getIntermediateResultManager(!0)),i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},J.postMessage({type:"cvr_createInstance",id:r}),i}async _singleFrameModeCallback(t){this._isa.getCameraView().setScanLaserVisible(!0);for(let e of this._resultReceiverSet)this._bNeedOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of this._resultReceiverSet)t.isDce&&t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});const r={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let e of this._resultReceiverSet)if(e.onDecodedBarcodesReceived&&i.barcodeResultItems&&e.onDecodedBarcodesReceived(Object.assign(Object.assign({},r),{barcodeResultItems:i.barcodeResultItems})),e.onRecognizedTextLinesReceived&&i.textLineResultItems&&e.onRecognizedTextLinesReceived(Object.assign(Object.assign({},r),{textLineResultItems:i.textLineResultItems})),e.onDetectedQuadsReceived&&i.detectedQuadResultItems&&e.onDetectedQuadsReceived(Object.assign(Object.assign({},r),{detectedQuadResultItems:i.detectedQuadResultItems})),e.onNormalizedImagesReceived&&i.normalizedImageResultItems&&e.onNormalizedImagesReceived(Object.assign(Object.assign({},r),{normalizedImageResultItems:i.normalizedImageResultItems})),e.onParsedResultsReceived&&i.parsedResultItems&&e.onParsedResultsReceived(Object.assign(Object.assign({},r),{parsedResultItems:i.parsedResultItems})),e.onCapturedResultReceived&&!e.isDce){if(this._bNeedOutputOriginalImage){const e=i.items.findIndex((t=>1===t.type));-1!==e&&(i.items[e].imageData=t)}e.onCapturedResultReceived(i)}}setInput(t){if(this._checkIsDisposed(),t){if(this._isa=t,t.isCameraEnhancer){this._intermediateResultManager&&(this._isa._intermediateResultReceiver.isDce=!0,this._intermediateResultManager.addResultReceiver(this._isa._intermediateResultReceiver));const t=this._isa.getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,this._resultReceiverSet.add(e)}}}else this._isa=null}getInput(){return this._isa}addImageSourceStateListener(t){if(this._checkIsDisposed(),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&this._isaStateListenerSet.add(t)}removeImageSourceStateListener(t){return this._checkIsDisposed(),this._isaStateListenerSet.delete(t)}addResultReceiver(t){if(this._checkIsDisposed(),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(this._resultReceiverSet.add(t),this._setCrrRegistry())}removeResultReceiver(t){this._checkIsDisposed(),this._resultReceiverSet.delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of this._resultReceiverSet)e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Zt;let i=$();return tt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},J.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(this._checkIsDisposed(),"object"!=typeof t)return console.warn("Invalid filter.");if(t&&Object.keys(t)){this._resultFilterSet.add(t),this._handleFilterSwitch();for(let t of this._resultFilterSet)await this._enableResultCrossVerification(t.verificationEnabled),await this._enableResultDeduplication(t.duplicateFilterEnabled),await this._setDuplicateForgetTime(t.duplicateForgetTime)}}async removeResultFilter(t){this._checkIsDisposed(),this._resultFilterSet.delete(t),this._handleFilterSwitch();for(let t of this._resultFilterSet)await this._enableResultCrossVerification(t.verificationEnabled),await this._enableResultDeduplication(t.duplicateFilterEnabled),await this._setDuplicateForgetTime(t.duplicateForgetTime)}_handleFilterSwitch(){this._bOpenBarcodeVerify=!1,this._bOpenLabelVerify=!1,this._bOpenDetectVerify=!1,this._bOpenNormalizeVerify=!1;for(let t of this._resultFilterSet)t.isResultCrossVerificationEnabled(dt.CRIT_BARCODE)&&(this._bOpenBarcodeVerify=!0),t.isResultCrossVerificationEnabled(dt.CRIT_TEXT_LINE)&&(this._bOpenLabelVerify=!0),t.isResultCrossVerificationEnabled(dt.CRIT_DETECTED_QUAD)&&(this._bOpenDetectVerify=!0),t.isResultCrossVerificationEnabled(dt.CRIT_NORMALIZED_IMAGE)&&(this._bOpenNormalizeVerify=!0)}async startCapturing(t){var e,i;if(this._checkIsDisposed(),!this._bPauseScan)return;if(!this._isa)throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const s=await this.containsTask(t);return await ct(s),s.includes("dlr")&&!(null===(e=ot.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)&&await(null===(i=ot.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",at.dlr)),this._isa.isCameraEnhancer&&(s.includes("ddn")?this._isa.setPixelFormat(n.IPF_ABGR_8888):this._isa.setPixelFormat(n.IPF_GRAYSCALED)),void 0!==this._isa.singleFrameMode&&"disabled"!==this._isa.singleFrameMode?(this._templateName=t,void this._isa.on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(this._isa.getColourChannelUsageType()===r.CCUT_AUTO&&this._isa.setColourChannelUsageType(s.includes("ddn")?r.CCUT_FULL_CHANNEL:r.CCUT_Y_CHANNEL_ONLY),this._promiseStartScan&&this._promiseStartScan.isPending?this._promiseStartScan:(this._promiseStartScan=new Zt(((e,i)=>{if(this.disposed)return;let r=$();tt[r]=async r=>{if(this._promiseStartScan&&!this._promiseStartScan.isFulfilled){if(!r.success){let t=new Error(r.message);return t.stack=r.stack+"\n"+t.stack,i(t)}for(let t of this._resultFilterSet)await this.addResultFilter(t);this._bPauseScan=!1,this._bNeedOutputOriginalImage=r.bNeedOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&this._isa.startFetching(),this._loopReadVideo(t),e()}),0),this._isa.isCameraEnhancer&&this._isa.getCameraView().setScanLaserVisible(!0)}},J.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:t}})})),await this._promiseStartScan))}stopCapturing(){this._checkIsDisposed(),this._isa&&(this._isa.isCameraEnhancer&&(this._isa.getCameraView().setScanLaserVisible(!1),void 0!==this._isa.singleFrameMode&&"disabled"!==this._isa.singleFrameMode)?this._isa.off("singleFrameAcquired",this._singleFrameModeCallbackBind):(this._isa.stopFetching(),this._clearVerifyList(),this._averageProcessintTimeArray=[],this._averageTime=999,this._bPauseScan=!0,this._promiseStartScan=null,this._isa.setColourChannelUsageType(r.CCUT_AUTO)))}async _clearVerifyList(){let t=$();const e=new Zt;return tt[t]=async t=>{if(t.success)return e.resolve();{let i=new Error(t.message);return i.stack=t.stack+"\n"+i.stack,e.reject(i)}},J.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e}async _getIntermediateResult(){this._checkIsDisposed();let t=$();const e=new Zt;return tt[t]=async t=>{if(t.success)e.resolve(t.result);else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject(i)}},J.postMessage({type:"cvr_getIntermediateResult",id:t,instanceID:this._instanceID}),e}async containsTask(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_containsTask",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(e){if(this._dynamsoft=!0,this.disposed||this._bPauseScan)return;if(this._isa.isBufferEmpty())if(this._isa.hasNextImageToFetch())for(let t of this._isaStateListenerSet)t.onImageSourceStateReceived&&t.onImageSourceStateReceived(oe.ISS_BUFFER_EMPTY);else if(!this._isa.hasNextImageToFetch())for(let t of this._isaStateListenerSet)t.onImageSourceStateReceived&&t.onImageSourceStateReceived(oe.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||this._isa.isBufferEmpty())try{this._isa.isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=this._isa.fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),this._isa.setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(this._isa.setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=this._isa.getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of this._resultReceiverSet)this._bNeedOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then((async r=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._bPauseScan)return void this._reRunCurrnetFunc(e);r.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of this._resultReceiverSet)if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(r,{isDetectVerifyOpen:this._bOpenDetectVerify,isNormalizeVerifyOpen:this._bOpenNormalizeVerify,isBarcodeVerifyOpen:this._bOpenBarcodeVerify,isLabelVerifyOpen:this._bOpenLabelVerify}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}const n={originalImageHashId:r.originalImageHashId,originalImageTag:r.originalImageTag,errorCode:r.errorCode,errorString:r.errorString};for(let t of this._resultReceiverSet)t.onDecodedBarcodesReceived&&r.barcodeResultItems&&t.onDecodedBarcodesReceived(Object.assign(Object.assign({},n),{barcodeResultItems:r.barcodeResultItems.filter((t=>!t.isFilter))})),t.onRecognizedTextLinesReceived&&r.textLineResultItems&&t.onRecognizedTextLinesReceived(Object.assign(Object.assign({},n),{textLineResultItems:r.textLineResultItems.filter((t=>!t.isFilter))})),t.onDetectedQuadsReceived&&r.detectedQuadResultItems&&t.onDetectedQuadsReceived(Object.assign(Object.assign({},n),{detectedQuadResultItems:r.detectedQuadResultItems.filter((t=>!t.isFilter))})),t.onNormalizedImagesReceived&&r.normalizedImageResultItems&&t.onNormalizedImagesReceived(Object.assign(Object.assign({},n),{normalizedImageResultItems:r.normalizedImageResultItems.filter((t=>!t.isFilter))})),t.onParsedResultsReceived&&r.parsedResultItems&&t.onParsedResultsReceived(Object.assign(Object.assign({},n),{parsedResultItems:r.parsedResultItems.filter((t=>!t.isFilter))})),t.onCapturedResultReceived&&!t.isDce&&(r.items=r.items.filter((t=>!t.isFilter)),r.barcodeResultItems&&(r.barcodeResultItems=r.barcodeResultItems.filter((t=>!t.isFilter))),r.textLineResultItems&&(r.textLineResultItems=r.textLineResultItems.filter((t=>!t.isFilter))),r.detectedQuadResultItems&&(r.detectedQuadResultItems=r.detectedQuadResultItems.filter((t=>!t.isFilter))),r.normalizedImageResultItems&&(r.normalizedImageResultItems=r.normalizedImageResultItems.filter((t=>!t.isFilter))),r.parsedResultItems&&(r.parsedResultItems=r.parsedResultItems.filter((t=>!t.isFilter))),t.onCapturedResultReceived(r));const s=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-s;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(e)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(e)}),Math.max(this._minImageCaptureInterval,0))})).catch((t=>{this._isa.stopFetching(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._isa.startFetching(),this._loopReadVideo(e)}),Math.max(this._minImageCaptureInterval,1e3)),"platform error"!==t.message&&setTimeout((()=>{throw t}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,r;this._checkIsDisposed(),e||(e=this._currentSettings.CaptureVisionTemplates[0].Name);const n=await this.containsTask(e);let s;if(await ct(n),n.includes("dlr")&&!(null===(i=ot.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)&&await(null===(r=ot.dlr)||void 0===r?void 0:r.loadRecognitionData("ConfusableChars",at.dlr)),this._dynamsoft=!1,d(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await w(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),r=i.length,n=new Uint8Array(r);for(;r--;)n[r]=i.charCodeAt(r);return await this._captureBlob(new Blob([n]),e)}async _captureBlob(t,e){let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await async function(t){return await new Promise(((e,i)=>{let r=URL.createObjectURL(t),n=new Image;n.src=r,n.onload=()=>{URL.revokeObjectURL(n.dbrObjUrl),e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._captureImage(i||r,e);return i&&i.close(),n}async _captureImage(t,e){let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);o>this.maxCvsSideLength?(this._compressRate=this.maxCvsSideLength/o,i=Math.round(n*this._compressRate),r=Math.round(s*this._compressRate)):(i=n,r=s),this._canvas||(this._canvas=document.createElement("canvas"));const a=this._canvas;return a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),r={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(r,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,r,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);o>this.maxCvsSideLength?(this._compressRate=this.maxCvsSideLength/o,i=Math.round(n*this._compressRate),r=Math.round(s*this._compressRate)):(i=n,r=s),this._canvas||(this._canvas=document.createElement("canvas"));const a=this._canvas;return a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:r,width:n,height:s,stride:o,format:a}=e;let h=$();const l=new Zt;return tt[h]=async i=>{var r,n;if(!i.success){let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,l.reject(t)}{const s=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${s}`),t._onLog("worker to main time consume: "+(s-i.workerReturnMsgTime)));try{const t=i.captureResult;e.bytes=i.bytes;for(let i of t.items)0!==this._compressRate&&he(i,this._compressRate),i.type===dt.CRIT_ORIGINAL_IMAGE?i.imageData=e:i.type===dt.CRIT_NORMALIZED_IMAGE?null===(r=ot.ddn)||void 0===r||r.handleNormalizedImageResultItem(i):i.type===dt.CRIT_PARSED_RESULT&&(null===(n=ot.dcp)||void 0===n||n.handleParsedResultItem(i));if(this._dynamsoft)for(let e of this._resultFilterSet)e.onDecodedBarcodesReceived(t.items),e.onRecognizedTextLinesReceived(t.items),e.onDetectedQuadsReceived(t.items),e.onNormalizedImagesReceived(t.items);const s=function(t){const e={barcodeResultItems:[],textLineResultItems:[],detectedQuadResultItems:[],normalizedImageResultItems:[],parsedResultItems:[]};return t.items.forEach((t=>{t.type===dt.CRIT_BARCODE?e.barcodeResultItems.push(t):t.type===dt.CRIT_TEXT_LINE?e.textLineResultItems.push(t):t.type===dt.CRIT_DETECTED_QUAD?e.detectedQuadResultItems.push(t):t.type===dt.CRIT_NORMALIZED_IMAGE?e.normalizedImageResultItems.push(t):t.type===dt.CRIT_PARSED_RESULT&&e.parsedResultItems.push(t)})),e}(t);if(s.barcodeResultItems.length&&(t.barcodeResultItems=s.barcodeResultItems),s.textLineResultItems.length&&(t.textLineResultItems=s.textLineResultItems),s.detectedQuadResultItems.length&&(t.detectedQuadResultItems=s.detectedQuadResultItems),s.normalizedImageResultItems.length&&(t.normalizedImageResultItems=s.normalizedImageResultItems),s.parsedResultItems.length&&(t.parsedResultItems=s.parsedResultItems),!this._bPauseScan||!this._dynamsoft){const i=t.intermediateResult;if(i){let t=0;for(let r of this._intermediateResultReceiverSet){t++;for(let n of i){if("onTaskResultsReceived"===n.info.callbackName){for(let t of n.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;r[n.info.callbackName]&&r[n.info.callbackName]({intermediateResultUnits:n.intermediateResultUnits},n.info)}else r[n.info.callbackName]&&r[n.info.callbackName](n.result,n.info);t===this._intermediateResultReceiverSet.size&&delete n.info.callbackName}}}t&&t.intermediateResult&&delete t.intermediateResult}return this._compressRate=0,l.resolve(t)}catch(i){return l.reject(i)}}},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),J.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:r,width:n,height:s,stride:o,format:a,templateName:i||"",dynamsoft:this._dynamsoft}},[r.buffer]),l}async initSettings(t){return this._checkIsDisposed(),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.startsWith("{")?this._currentSettings=JSON.parse(t):t=await w(t,"text"):"object"==typeof t&&(this._currentSettings=t,t=JSON.stringify(t)),await new Promise(((e,i)=>{let r=$();tt[r]=async r=>{if(r.success){const n=JSON.parse(r.response);if(0!==n.exception){let t=new Error(n.description?n.description:"Init Settings Failed.");return t.errorCode=n.exception,i(t)}let s=[],o=JSON.parse(t).CaptureVisionTemplates;for(let t=0;t{let r=$();tt[r]=async t=>{if(t.success){const r=JSON.parse(t.settings);if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,i(t)}return delete r.errorCode,delete r.errorString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const r=await this.outputSettings(t),n=new Blob([JSON.stringify(r,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(n),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return n}async getSimplifiedSettings(t){this._checkIsDisposed(),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await ct(e),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success){const r=JSON.parse(t.settings,((t,e)=>T&&"barcodeFormatIds"===t?BigInt(e):e));if(r.minImageCaptureInterval=this._minImageCaptureInterval,0!==r.code){let t=new Error(r.codeString);return t.errorCode=r.errorCode,i(t)}return delete r.code,delete r.codeString,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_getSimplifiedSettings",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){this._checkIsDisposed();const i=await this.containsTask(t);return await ct(i),await new Promise(((i,r)=>{let n=$();tt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._bNeedOutputOriginalImage=t.bNeedOutputOriginalImage,0!==n.exception){let t=new Error(n.description?n.description:"Update Settings Failed.");return t.errorCode=n.exception,r(t)}return this._currentSettings=await this.outputSettings("*"),i(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,r(e)}},J.postMessage({type:"cvr_updateSettings",id:n,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return this._checkIsDisposed(),await new Promise(((t,e)=>{let i=$();tt[i]=async i=>{if(i.success){const r=JSON.parse(i.response);if(0!==r.exception){let t=new Error(r.description?r.description:"Reset Settings Failed.");return t.errorCode=r.exception,e(t)}return this._currentSettings=await this.outputSettings("*"),t(r)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},J.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return this._bufferdItemsManager||(this._bufferdItemsManager=new Kt(this)),this._bufferdItemsManager}getIntermediateResultManager(t){if(this._checkIsDisposed(),!t&&0!==ut.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return this._intermediateResultManager||(this._intermediateResultManager=new Qt(this)),this._intermediateResultManager}contains(t,e){return function(t,e){let i=e.x,r=e.y,n=t[0].x,s=t[0].y,o=t[1].x,a=t[1].y,h=t[2].x,l=t[2].y,c=t[3].x,u=t[3].y,d=p(i,r,n,s,o,a),f=p(i,r,o,a,h,l),g=p(i,r,h,l,c,u),m=p(i,r,c,u,n,s);function p(t,e,i,r,n,s){return(t-i)*(s-r)-(e-r)*(n-i)}return d>=0&&f>=0&&g>=0&&m>=0||d<=0&&f<=0&&g<=0&&m<=0}(t,e)}async parseRequiredResources(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_parseRequiredResources",id:r,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){this._checkIsDisposed(),this._promiseStartScan&&this.stopCapturing(),this._isa=null,this._resultReceiverSet.clear(),this._isaStateListenerSet.clear(),this._resultFilterSet.clear(),this.bDestroyed=!0;let t=$();tt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},J.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}async _enableResultCrossVerification(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:this._instanceID,body:{verificationEnabled:t}})}))}async _enableResultDeduplication(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})}))}async _setDuplicateForgetTime(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:this._instanceID,body:{duplicateForgetTime:t}})}))}async _getDuplicateForgetTime(t){return this._checkIsDisposed(),await new Promise(((e,i)=>{let r=$();tt[r]=async t=>{if(t.success)return e(t.time);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},J.postMessage({type:"cvr_getDuplicateForgetTime",id:r,instanceID:this._instanceID,body:{type:t}})}))}async _setThresholdValue(t,e,i){return await ct("ddn"),await new Promise(((r,n)=>{let s=$();tt[s]=async t=>{if(t.success)return r();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},J.postMessage({type:"ddn_setThresholdValue",id:s,instanceID:this._instanceID,body:{threshold:t,leftLimit:e,rightLimit:i}})}))}_checkIsDisposed(){if(this.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}},ce=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},ue=class{constructor(){this._observedResultUnitTypes=wt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}};const de="undefined"==typeof self,fe=(()=>{if(!de&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();null==at.dce&&(at.dce=fe),lt.dce={wasm:!1,js:!1},ot.dce={};let ge,me,pe,_e,ve,ye=class{static getVersion(){return"4.0.3"}};function we(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function Ee(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(ge=navigator,me=ge.userAgent,pe=ge.platform,_e=ge.mediaDevices),function(){if(!de){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:ge.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:pe,search:"Win"},Mac:{str:pe},Linux:{str:pe}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||me,o=n.search||e,a=n.verStr||me,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||me,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=me.indexOf("Windows NT")&&(n="HarmonyOS"),ve={browser:i,version:r,OS:n}}de&&(ve={browser:"ssr",version:0,OS:"ssr"})}();const Ce="undefined"!=typeof WebAssembly&&me&&!(/Safari/.test(me)&&!/Chrome/.test(me)&&/\(.+\s11_2_([2-6]).*\)/.test(me)),Te=!("undefined"==typeof Worker),be=!(!_e||!_e.getUserMedia),Se=async()=>{let t=!1;if(be)try{(await _e.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===ve.browser&&ve.version>66||"Safari"===ve.browser&&ve.version>13||"OPR"===ve.browser&&ve.version>43||"Edge"===ve.browser&&ve.version;var Ie={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,E,C,T,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var S=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=S.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=S,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,r=e.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 x(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,n=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new b.Point(t.x-e.x,t.y-e.y),n=b.util.rotateVector(r,i);return new b.Point(n.x,n.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),r=b.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=b.util.createVector(t,e),n=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(r,n),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(r,s),n)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var n,s=!0,o=t.getImageData(e,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(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var T=Math.sqrt(1-E/(_*v));i*=T,s*=T}else C=(o===a?-1:1)*Math.sqrt(E/(_*y+v*w));var S=C*i*p/s,I=-C*s*m/i,x=d*S-u*I+.5*t,A=u*S+d*I+.5*e,R=n(1,0,(m-S)/i,(p-I)/s),O=n((m-S)/i,(p-I)/s,(-m-S)/i,(-p-I)/s);0===a&&O>0?O-=2*l:1===a&&O<0&&(O+=2*l);for(var D=Math.ceil(Math.abs(O/l*2)),L=[],M=O/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kC)for(var S=1,I=m.length;S2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,r,n,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],T=[[],[]];u=6*e-12*r+6*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;for(var S=0;S<2;++S)if(S>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var I,x,A,R=C.length,O=R;R--;)I=(A=1-(f=C[R]))*A*A*e+3*A*A*f*r+3*A*f*f*s+f*f*f*a,T[0][R]=I,x=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,T[1][R]=x;T[0][O]=e,T[1][O]=i,T[0][O+1]=a,T[1][O+1]=h;var D=[{x:y.apply(null,T[0]),y:y.apply(null,T[1])},{x:w.apply(null,T[0]),y:w.apply(null,T[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},n=1;n=e}))}}}(),function(){function t(e,i,r){if(r)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var n=0,s=i.length;n57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var n=t.charCodeAt(e-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?m(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=b.document.documentElement,n=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,r,n=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function r(){return!1}function n(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,m=i.easing||n,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,w=p?_.map((function(t,e){return m(r,_[e],y[e],c)})):m(r,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=n,!o){if(!f(w,E,n))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,E,n),void a(t));h()}}(l)})),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,r,n){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},b.util.animate(b.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,n,s,o=[];for(n=0,s=e.length;n1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,n,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",T=0,b=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),E.minX=i,E.minY=r,E.viewBoxWidth=n,E.viewBoxHeight=o,y?(E.width=n,E.height=o):(E.width=s(d),E.height=s(f),c=E.width/n,u=E.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),T=E.width-n*c,b=E.height-o*c,"Mid"===p.alignX&&(T/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(T=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+T)+" "+(r*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),E}function w(t,e){var i="xlink:href",r=_(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&w(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:n=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),r.fire(t,i)}function m(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function E(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(t){return t.flipX!==t.flipY}function T(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function b(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=E(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),C(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",n),T(l,"skewY","scaleY","y",p)}return m}function S(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=E(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.originY===o&&(n=-n),C(l)&&(n=-n));var m=g!==n;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",n),T(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,w=m(t,f),C=_(f,y,w),T=e.gestureScale;if(C)return!1;if(T)o=e.scaleX*T,a=e.scaleY*T;else{if(s=E(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),S=e.original,I=b/(Math.abs(h.x*S.scaleX/f.scaleX)+Math.abs(h.y*S.scaleY/f.scaleY));o=S.scaleX*I,a=S.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=m(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=w("rotating",y((function(t,e,i,r){var n=e,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,w("skewing",y(b))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=E(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,w("skewing",y(S))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},n.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=w,n.getLocalPoint=E,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new b.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,n,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=m/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,r,n=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.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,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,r),offsetY:_(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,n=this.offsetX/t.width,s=this.offsetY/t.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))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.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(t){var r=40,n=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.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 t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,r=b.util.toFixed,n=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?b.util.loadImage(e,(function(e,n){if(e){var s=new b.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,n=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?b.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,o,a,h="",l={},c=b.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new b.Point(r.x,r.y),n=new b.Point(n.x,n.y),r.x-=s,n.x+=s}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=b.util.invertTransform(i),n=this.restorePointerVpt(e);return b.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),r=b.util.transformPoint(i,this.viewportTransform),n=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,n,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).subTargetCheck&&i instanceof b.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e,selected:n}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==r&&(b.Canvas[r]=b.StaticCanvas[r])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,n=this._getEventPrefix();t(b.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new b.Point(v(r,s),v(n,o)),h=new b.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,t);return b.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):b.util.object.clone(t),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],(function(e){n[t]=e[0],i[t]=!0,r&&r()})):this["set"+b.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=l>y||c>w;v=E||(l<.9*y||c<.9*w)&&y>h&&w>h,E&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,n=this[t]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,n,s){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new o(i[s],i):new o(i);n&&n(t)}))}))},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,n){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof r?r=E[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(r,t,w(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(r,t,w(this.angle)):r},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),n=new b.Point(t.x,t.y),this.angle&&(n=b.util.rotatePoint(n,s,-w(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=w(this.angle),n=this.getScaledWidth(),s=b.util.cos(r)*n,o=b.util.sin(r)*n;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var n=this.getCoords(i,r);return"Intersection"===b.Intersection.intersectPolygonRectangle(n,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,r){var n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=b.util.sizeAfterTransform(this.width,this.height,e),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=b.util.transformPoint(r,i)),n.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.remove(t),r()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==n[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,n=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new e.Circle(n))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(n?e.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,n=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(n(t,"x")||0)-e,height:(n(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,n=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(t){return n(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return b.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=n,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var n=b.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(n*i,c-d),m=o(s*r,u-f),p=-n/2,_=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],b.util.enlivenObjectEnlivables(i,i,(function(){var r=new b.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,(function(t,r){e&&e(new b.Image(t,i),r)}),null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,r){var n=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(n["xlink:href"],i,e(r?b.util.object.clone(r):{},n))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,n=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){b.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=n,n},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),n},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,n,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,r+=m[h+2]*l,T||(n+=m[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=T?m[s+3]:n}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,n,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=r(1e3*s(b-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=o||(M=r(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(n(i(L*p,2)+i(M*_,2))/1e3)),(S=w[L][M])>0&&(x+=S,A+=S*c[I=4*(F*e+b)],R+=S*c[I+1],O+=S*c[I+2],D+=S*c[I+3]))}d[I=4*(T*a+h)]=A/x,d[I+1]=R/x,d[I+2]=O/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(S+=y*f[3+(L=4*(D+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],T+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=T/w,m[v+2]=b/w,m[v+3]=S/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,n=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,n){var s,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,n=e.length;r0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,r=n,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+C*r+o,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,n=this.fontFamily,s=e.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,n,s=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,E=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,E=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+E,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var n in e.styles[r])t(e.styles[r][n]);b.Object._fromObject("IText",e,i,"text")}}(),T=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),n=b.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=T(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:T(r[i-1])}:n?this.styles[t+i]={0:T(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?T(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=T(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=T(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+n>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+n),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},xe={};function Ae(t){var e=xe[t];if(void 0!==e)return e.exports;var i=xe[t]={exports:{}};return Ie[t](i,i.exports,Ae),i.exports}Ae.d=(t,e)=>{for(var i in e)Ae.o(e,i)&&!Ae.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},Ae.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Re={};(()=>{let t;Ae.d(Re,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?Ae(653).fabric:{version:"5.2.1"}})();var Oe,De,Le,Me,Fe=Re.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(Oe||(Oe={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(De||(De={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(Le||(Le={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Me||(Me={}));const Pe=t=>"number"==typeof t&&!Number.isNaN(t),ke=t=>"string"==typeof t;var Be,Ne,Ue,je,Ge,We;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(Ge||(Ge={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(We||(We={}));class Ve{get mediaType(){return new Map([["rect",Oe.DIMT_RECTANGLE],["quad",Oe.DIMT_QUADRILATERAL],["text",Oe.DIMT_TEXT],["arc",Oe.DIMT_ARC],["image",Oe.DIMT_IMAGE],["polygon",Oe.DIMT_POLYGON],["line",Oe.DIMT_LINE],["group",Oe.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(we(this,Ne,"f")){case De.DIS_DEFAULT:return"default";case De.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===we(this,Ue,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===we(this,Ue,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ee(this,Ue,t,"f")}get coordinateBase(){return we(this,Ue,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(Be.add(this),Ne.set(this,void 0),Ue.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!Pe(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(De.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(De.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(De.DIS_SELECTED):this.setState(De.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ee(this,Ne,t,"f")}getState(){return we(this,Ne,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let n=r.get(e);n||(n=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)unull!==t&&"object"==typeof t&&!Array.isArray(t),He=t=>!!ke(t)&&""!==t,Xe=d,ze=f,Ze=m,Ke=_,qe=p,Je=v,Qe=y,$e=t=>!(!Ye(t)||"id"in t&&!Pe(t.id)||"lineWidth"in t&&!Pe(t.lineWidth)||"fillStyle"in t&&!He(t.fillStyle)||"strokeStyle"in t&&!He(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!He(t.fontFamily)||"fontSize"in t&&!Pe(t.fontSize));class ti{static convert(t,e,i){const r={x:0,y:0,width:e,height:i};if(!t)return r;if(Qe(t))t.isMeasuredInPercentage?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height);else{if(!ze(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var ei,ii;class ri{constructor(){ei.set(this,new Map),ii.set(this,!1)}get disposed(){return we(this,ii,"f")}on(t,e){t=t.toLowerCase();const i=we(this,ei,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else we(this,ei,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=we(this,ei,"f").get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){t=t.toLowerCase();const e=we(this,ei,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const r=we(this,ei,"f").get(t);if(r&&r.length){i=Object.assign({async:!1,copy:!0},i);for(let n of r){if(!n)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout((()=>{this.disposed||r.includes(n)&&n.apply(i.target,s)}),0);else try{o=n.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ee(this,ii,!0,"f")}}function ni(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function si(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function oi(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s||(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),(n^s)>=0&&0!==n&&0!==s))}ei=new WeakMap,ii=new WeakMap;const ai=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const r=document.createElement("div");r.insertAdjacentHTML("beforeend",i);for(let t=0;t0?i-1:r,pi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ee(this,li,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new Fe.Control({positionHandler:gi,actionHandler:_i(r>0?r-1:i,pi),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,n=i.y-e.pathOffset.y;const s=Fe.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){we(this,li,"f")&&this.setPolygon(we(this,li,"f"))}setPolygon(t){if(!Ke(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ee(this,li,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return we(this,li,"f")?JSON.parse(JSON.stringify(we(this,li,"f"))):null}}li=new WeakMap;class yi extends Ve{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return we(this,ui,"f")}constructor(t,e,i,r){if(super(null,r),ci.set(this,void 0),ui.set(this,void 0),!Qe(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new Fe.Image(t,{left:e.x,top:e.y}));else{if(!Xe(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let r;if(i.width=t.width,i.height=t.height,t.format===n.IPF_GRAYSCALED){r=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new Fe.Control({positionHandler:gi,actionHandler:_i(i>0?i-1:r,pi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,n=t.y-i.pathOffset.y;const s=Fe.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){we(this,Ci,"f")&&this.setLine(we(this,Ci,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!Ze(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ee(this,Ci,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return we(this,Ci,"f")?JSON.parse(JSON.stringify(we(this,Ci,"f"))):null}}Ci=new WeakMap;class sr extends vi{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Ti.set(this,void 0),!Je(t))throw new TypeError("Invalid 'quad'.");Ee(this,Ti,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){we(this,Ti,"f")&&this.setQuad(we(this,Ti,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!Je(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ee(this,Ti,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return we(this,Ti,"f")?JSON.parse(JSON.stringify(we(this,Ti,"f"))):null}}Ti=new WeakMap;class or extends Ve{constructor(t){super(new Fe.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(De.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(De.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}class ar{static createDrawingStyle(t){if(!$e(t))throw new Error("Invalid style definition.");let e,i=ar.USER_START_STYLE_ID;for(;we(ar,bi,"f",Si).has(i);)i++;e=i;const r=JSON.parse(JSON.stringify(t));r.id=e;for(let t in we(ar,bi,"f",Ii))r.hasOwnProperty(t)||(r[t]=we(ar,bi,"f",Ii)[t]);return we(ar,bi,"f",Si).set(e,r),r.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=we(ar,bi,"f",Si).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(we(ar,bi,"f",Si).values())))}static _updateDrawingStyle(t,e){if(!$e(e))throw new Error("Invalid style definition.");const i=we(ar,bi,"f",Si).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}bi=ar,ar.STYLE_BLUE_STROKE=1,ar.STYLE_GREEN_STROKE=2,ar.STYLE_ORANGE_STROKE=3,ar.STYLE_YELLOW_STROKE=4,ar.STYLE_BLUE_STROKE_FILL=5,ar.STYLE_GREEN_STROKE_FILL=6,ar.STYLE_ORANGE_STROKE_FILL=7,ar.STYLE_YELLOW_STROKE_FILL=8,ar.STYLE_BLUE_STROKE_TRANSPARENT=9,ar.STYLE_GREEN_STROKE_TRANSPARENT=10,ar.STYLE_ORANGE_STROKE_TRANSPARENT=11,ar.USER_START_STYLE_ID=1024,Si={value:new Map([[ar.STYLE_BLUE_STROKE,{id:ar.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[ar.STYLE_GREEN_STROKE,{id:ar.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_ORANGE_STROKE,{id:ar.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_YELLOW_STROKE,{id:ar.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[ar.STYLE_BLUE_STROKE_FILL,{id:ar.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_GREEN_STROKE_FILL,{id:ar.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_ORANGE_STROKE_FILL,{id:ar.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_YELLOW_STROKE_FILL,{id:ar.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_BLUE_STROKE_TRANSPARENT,{id:ar.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_GREEN_STROKE_TRANSPARENT,{id:ar.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[ar.STYLE_ORANGE_STROKE_TRANSPARENT,{id:ar.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Ii={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(Fe.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(Fe.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),Fe.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},Fe.Object.prototype.transparentCorners=!1,Fe.Object.prototype.cornerSize=20,Fe.Object.prototype.touchCornerSize=100,Fe.Object.prototype.cornerColor="rgb(254,142,20)",Fe.Object.prototype.cornerStyle="circle",Fe.Object.prototype.strokeUniform=!0,Fe.Object.prototype.hasBorders=!1,Fe.Canvas.prototype.containerClass="",Fe.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,r=this.upperCanvasEl,n=Fe.util.getPointer(t,r),s=r.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=this.restorePointerVpt(n));var h=this.getRetinaScaling();if(1!==h&&(n.x/=h,n.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(r).objectFit,c=r.width,u=r.height,d=o,f=a;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>_?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},Fe.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();Fe.util.addListener(Fe.document,"touchend",this._onTouchEnd,{passive:!1}),Fe.util.addListener(Fe.document,"touchmove",this._onMouseMove,{passive:!1}),Fe.util.removeListener(i,r+"down",this._onMouseDown)},Fe.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?Fe.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class hr{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new Fe.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],n=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&n.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(r,n)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let r,n;switch(this.id=e,e){case hr.DDN_LAYER_ID:r=ar.getDrawingStyle(ar.STYLE_BLUE_STROKE),n=ar.getDrawingStyle(ar.STYLE_BLUE_STROKE_FILL);break;case hr.DBR_LAYER_ID:r=ar.getDrawingStyle(ar.STYLE_ORANGE_STROKE),n=ar.getDrawingStyle(ar.STYLE_ORANGE_STROKE_FILL);break;case hr.DLR_LAYER_ID:r=ar.getDrawingStyle(ar.STYLE_GREEN_STROKE),n=ar.getDrawingStyle(ar.STYLE_GREEN_STROKE_FILL);break;default:r=ar.getDrawingStyle(ar.STYLE_YELLOW_STROKE),n=ar.getDrawingStyle(ar.STYLE_YELLOW_STROKE_FILL)}for(let t of Ve.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:r.id,selected:n.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return ar.getDrawingStyle(t.styleId);return ar.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){const n=this.getDrawingItems((e=>e._mediaType===t));for(let t of n)t.styleSelector===e&&this._changeItemStyle(t,i,!0);r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=ar.getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildDrawingItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=ar.getDrawingStyle(e.styleId);else{const r=this.mapType_StateAndStyleId.get(e._mediaType);i=ar.getDrawingStyle(r[t.styleSelector]);const n=()=>{this._changeItemStyle(e,ar.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,ar.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",n),e._on("deselected",s),e._funcChangeStyleToSelected=n,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Ve))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildDrawingItems();for(let t of n)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(n){for(let t of n){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ve.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=ar.getDrawingStyle(t.styleId);else{s=ar.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,ar.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},r=()=>{this._changeItemStyle(t,ar.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ve.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=ar.getDrawingStyle(t.styleId);else{s=ar.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,ar.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},r=()=>{this._changeItemStyle(t,ar.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase())):e=Ve.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=Ve.arrStyleSelectors;const r=ar.getDrawingStyle(t);if(!r)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let n;for(let s of e)if(n=this.mapType_StateAndStyleId.get(s),n)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,r,!0),n[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const r=[];i&Oe.DIMT_RECTANGLE&&r.push("rect"),i&Oe.DIMT_QUADRILATERAL&&r.push("quad"),i&Oe.DIMT_TEXT&&r.push("text"),i&Oe.DIMT_ARC&&r.push("arc"),i&Oe.DIMT_IMAGE&&r.push("image"),i&Oe.DIMT_POLYGON&&r.push("polygon"),i&Oe.DIMT_LINE&&r.push("line");const n=[];e&De.DIS_DEFAULT&&n.push("default"),e&De.DIS_SELECTED&&n.push("selected"),this._setDefaultStyle(t,r.length?r:null,n.length?n:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}hr.DDN_LAYER_ID=1,hr.DBR_LAYER_ID=2,hr.DLR_LAYER_ID=3,hr.USER_DEFINED_LAYER_BASE_ID=100,hr.TIP_LAYER_ID=999;class lr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new hr(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class cr extends Ei{constructor(t,e,i,r,n){super(t,{x:e,y:i,width:r,height:0},n),xi.set(this,void 0),Ai.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ee(this,Ai,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),we(this,xi,"f")),"f")}getDuration(){return we(this,xi,"f")}}xi=new WeakMap,Ai=new WeakMap;class ur{constructor(){Ri.add(this),Oi.set(this,void 0),Di.set(this,void 0),Li.set(this,void 0),Mi.set(this,!0),this._drawingLayerManager=new lr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const r=document.createElement("canvas");return r.width==t&&r.height==e||(r.width=t,r.height=e),r.style.objectFit=i,r}_createDrawingLayer(t,e,i,r){if(!this._layerBaseCvs){let n;try{n=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==n?void 0:n.width)||1280),i||(i=(null==n?void 0:n.height)||720),r||(r=(null==n?void 0:n.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,r)}const n=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(n,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",n.parentElement),s}createDrawingLayer(){let t;for(let e=hr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==hr.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==hr.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Ye(e=t)&&qe(e.topLeftPoint)&&Pe(e.width))||e.width<=0||!Pe(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ee(this,Oi,JSON.parse(JSON.stringify(t)),"f"),we(this,Oi,"f").coordinateBase||(we(this,Oi,"f").coordinateBase="view"),Ee(this,Li,t.duration,"f"),we(this,Ri,"m",Bi).call(this)}getTipConfig(){return we(this,Oi,"f")?we(this,Oi,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ee(this,Mi,t,"f")}isTipVisible(){return we(this,Mi,"f")}updateTipMessage(t){if(!we(this,Oi,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=ar.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(hr.TIP_LAYER_ID)||this._createDrawingLayer(hr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=we(this,Ri,"m",Fi).call(this,t,we(this,Oi,"f").topLeftPoint.x,we(this,Oi,"f").topLeftPoint.y,we(this,Oi,"f").width,we(this,Oi,"f").coordinateBase,this._tipStyleId),we(this,Ri,"m",Pi).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",we(this,Mi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),we(this,Di,"f")&&clearTimeout(we(this,Di,"f")),we(this,Li,"f")>=0&&Ee(this,Di,setTimeout((()=>{we(this,Ri,"m",ki).call(this)}),we(this,Li,"f")),"f")}}Oi=new WeakMap,Di=new WeakMap,Li=new WeakMap,Mi=new WeakMap,Ri=new WeakSet,Fi=function(t,e,i,r,n,s){const o=new cr(t,e,i,r,s);return o.coordinateBase=n,o},Pi=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},ki=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},Bi=function(){if(!this._tip)return;const t=we(this,Oi,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class dr extends HTMLElement{constructor(){super(),Ni.set(this,void 0);const t=document.createElement("template").content,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ee(this,Ni,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const r=document.createElement("slot");r.setAttribute("name","content"),e.append(r);const n=document.createElement("slot");n.setAttribute("name","drawing-layer"),e.append(n);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t.cloneNode(!0))}getWrapper(){return we(this,Ni,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}Ni=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",dr);class fr extends HTMLElement{constructor(){super();const t=window._dce_default_template.content;this.attachShadow({mode:"open"}).appendChild(t.cloneNode(!0))}showScanLaser(){const t=this.shadowRoot.querySelector(".dce-scanlight");t&&(t.style.display="")}hideScanLaser(){const t=this.shadowRoot.querySelector(".dce-scanlight");t&&(t.style.display="none")}getElement(t){return this.shadowRoot.querySelector(t)}getVideoContainer(){return this.shadowRoot.querySelector(".dce-video-container")}getScanAreaEl(){return this.shadowRoot.querySelector(".dce-scanarea")}getScanLightEl(){return this.shadowRoot.querySelector(".dce-scanlight")}getLoadingBackgroundEl(){return this.shadowRoot.querySelector(".dce-bg-loading")}getCameraBackgroundEl(){return this.shadowRoot.querySelector(".dce-bg-camera")}getCameraSelectEl(){return this.shadowRoot.querySelector(".dce-sel-camera")}getResolutionSelectEl(){return this.shadowRoot.querySelector(".dce-sel-resolution")}getResolutionOptionEl(){return this.shadowRoot.querySelector(".dce-opt-gotResolution")}getCloseBtnEl(){return this.shadowRoot.querySelector(".dce-btn-close")}getDLRSelectEl(){return this.shadowRoot.querySelector(".dlr-sel-minletter")}getDLROptionEl(){return this.shadowRoot.querySelector(".dlr-opt-gotMinLtr")}}class gr extends ur{static get engineResourcePath(){return ut.engineResourcePaths.dce}static set defaultUIElementURL(t){gr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=gr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",gr.engineResourcePath)}static async createInstance(t){customElements.get(gr.uiComponentName)||customElements.define(gr.uiComponentName,fr);const e=new gr;return await e.setUIElement(t||gr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,r,n,s,o){const a=s/r,h=o/n;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==we(this,Zi,"f")){if(Ee(this,Zi,t,"f"),we(this,Ui,"m",Ji).call(this))Ee(this,Vi,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!we(this,Vi,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ve.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ee(this,Vi,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}we(this,Ui,"m",Ji).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return we(this,Zi,"f")}get disposed(){return we(this,qi,"f")}constructor(){super(),Ui.add(this),ji.set(this,void 0),Gi.set(this,void 0),Wi.set(this,void 0),this.containerClassName="dce-video-container",Vi.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,Yi.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Hi.set(this,!1),Xi.set(this,!1),zi.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{we(this,Ui,"m",ir).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&we(this,Ui,"m",er).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{gr._onLog&&gr._onLog("window resize event triggered."),we(this,zi,"f").width===document.documentElement.clientWidth&&we(this,zi,"f").height===document.documentElement.clientHeight||(we(this,zi,"f").width=document.documentElement.clientWidth,we(this,zi,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Zi.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!we(this,Ui,"m",Ji).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,r)=>{t.width==i&&t.height==r||(t.width=i,t.height=r);const n=t.getContext("2d");n.clearRect(0,0,t.width,t.height),n.drawImage(e,0,0)},r=await t(e),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,r,n,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Ki.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,r,n,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(r=o.cropRegion)||void 0===r?void 0:r.top)||0,c=(null===(n=o.cropRegion)||void 0===n?void 0:n.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,r,n,s,o,a,h=[],l)=>{e.forEach((t=>gr._transformCoordinates(t,i,r,n,s,o,a)));const c=new sr({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),we(this,Ki,"f").push(c)};let m,p;for(let t of a)switch(t.type){case dt.CRIT_ORIGINAL_IMAGE:break;case dt.CRIT_BARCODE:m=this.getDrawingLayer(hr.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,ar.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case dt.CRIT_TEXT_LINE:m=this.getDrawingLayer(hr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,ar.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case dt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(hr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],ar.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case dt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(hr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],ar.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case dt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},qi.set(this,!1),this.eventHandler=new ri,this.eventHandler.on("content:updated",(()=>{we(this,ji,"f")&&clearTimeout(we(this,ji,"f")),Ee(this,ji,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0),"f")})),this.eventHandler.on("videoEl:resized",(()=>{we(this,Gi,"f")&&clearTimeout(we(this,Gi,"f")),Ee(this,Gi,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0),"f")}))}_setUIElement(t){t instanceof HTMLTemplateElement?(window._dce_default_template=t,this.UIElement=new fr):this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if(e="string"==typeof t?await ai(t):t,e instanceof HTMLDivElement&&0==e.childElementCount){const t=await ai(gr.defaultUIElementURL);t instanceof HTMLTemplateElement?(window._dce_default_template=t,e.append(new fr)):e.append(t),this._setUIElement(e)}else this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let e,i=this.UIElement;if(i instanceof fr?e=i.getElement(`.${this.containerClassName}`):i instanceof HTMLDivElement&&1===i.childElementCount&&i.firstElementChild instanceof fr?(e=i.firstElementChild.getElement(`.${this.containerClassName}`),i=i.firstElementChild):e=i.classList.contains(this.containerClassName)?i:i.querySelector(`.${this.containerClassName}`),!e)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=new dr,e.appendChild(this._innerComponent),we(this,Ui,"m",Ji).call(this));else{const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ve.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ee(this,Vi,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(i instanceof fr?(this._selRsl=i.getElement(".dce-sel-resolution"),this._selMinLtr=i.getElement(".dlr-sel-minletter"),this._divScanArea=i.getElement(".dce-scanarea"),this._divScanLight=i.getElement(".dce-scanlight"),this._bgLoading=i.getElement(".dce-bg-loading"),this._bgCamera=i.getElement(".dce-bg-camera"),this._selCam=i.getElement(".dce-sel-camera"),this._optGotRsl=i.getElement(".dce-opt-gotResolution"),this._btnClose=i.getElement(".dce-btn-close"),this._optGotMinLtr=i.getElement(".dlr-opt-gotMinLtr")):(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr")),this._selRsl&&(this._hideDefaultSelection||we(this,Ui,"m",Ji).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||we(this,Ui,"m",Ji).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||we(this,Ui,"m",ir).call(this),we(this,Ui,"m",Ji).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),we(this,Ui,"m",Ji).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;gr._onLog&&gr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const e=null===(t=this._innerComponent)||void 0===t?void 0:t.getWrapper();e&&this._resizeObserver.observe(e)}we(this,zi,"f").width=document.documentElement.clientWidth,we(this,zi,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,r;we(this,Ui,"m",Ji).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),we(this,Ui,"m",ir).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ee(this,Vi,null,"f"),null===(r=this._videoContainer)||void 0===r||r.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(!this._selCam)return;let i;this._selCam.textContent="";for(let r of e){const e=document.createElement("option");e.value=r.deviceId,e.innerText=r.label,this._selCam.append(e),r.deviceId&&t&&t.deviceId==r.deviceId&&(i=e)}this._selCam.value=i?i.value:""}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"))}getVideoElement(){return we(this,Vi,"f")}isVideoLoaded(){return!!we(this,Vi,"f")&&4==we(this,Vi,"f").readyState}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!we(this,Vi,"f"))return;if(we(this,Vi,"f").style.objectFit=t,we(this,Ui,"m",Ji).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}we(this,Ui,"m",rr).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,r;let n,s,o;if(we(this,Ui,"m",Ji).call(this)?(n=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(r=this._cvsSingleFrameMode)||void 0===r?void 0:r.height,o="contain"):(n=null===(t=we(this,Vi,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=we(this,Vi,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!n||!s)throw new Error("Invalid content dimensions.");return{width:n,height:s,objectFit:o}}updateConvertedRegion(t){const e=ti.convert(this.scanRegion,t.width,t.height);Ee(this,Yi,e,"f"),we(this,Wi,"f")&&clearTimeout(we(this,Wi,"f")),Ee(this,Wi,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}we(this,Ui,"m",Qi).call(this,t,e),we(this,Ui,"m",rr).call(this,t,e)}),0),"f")}getConvertedRegion(){return we(this,Yi,"f")}setScanRegion(t){if(null!=t&&!ze(t)&&!Qe(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=we(this,Vi,"f").videoWidth,i=we(this,Vi,"f").videoHeight,r=this.getVideoFit(),{width:n,height:s}=this._innerComponent.getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===r&&(n/s1){const t=we(this,Vi,"f").videoWidth,e=we(this,Vi,"f").videoHeight,{width:r,height:n}=this._innerComponent.getBoundingClientRect(),s=t/e;if(r/nt.remove())),we(this,Ki,"f").length=0}dispose(){this._unbindUI(),delete window._dce_default_template,this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"disposed",{value:!0})}}function mr(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function pr(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}ji=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Vi=new WeakMap,Yi=new WeakMap,Hi=new WeakMap,Xi=new WeakMap,zi=new WeakMap,Zi=new WeakMap,Ki=new WeakMap,qi=new WeakMap,Ui=new WeakSet,Ji=function(){return"disabled"!==this._singleFrameMode},Qi=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},$i=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},tr=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},er=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},ir=function(){this._divScanLight&&(this._divScanLight.style.display="none")},rr=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:r,objectFit:n}=t;e||(e={x:0,y:0,width:i,height:r});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/r;let l,c,u,d,f=1;if("contain"===n)a66||"Safari"===Cr.browser&&Cr.version>13||"OPR"===Cr.browser&&Cr.version>43||"Edge"===Cr.browser&&Cr.version,"function"==typeof SuppressedError&&SuppressedError;let Sr=class t{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,i,r){return t.multiply(e,[1,0,0,0,1,0,i,r,1])}static rotate(e,i){var r=Math.cos(i),n=Math.sin(i);return t.multiply(e,[r,-n,0,n,r,0,0,0,1])}static scale(e,i,r){return t.multiply(e,[i,0,0,0,r,0,0,0,1])}};var Ir,xr,Ar,Rr,Or,Dr,Lr,Mr,Fr,Pr,kr,Br,Nr,Ur,jr,Gr,Wr,Vr,Yr,Hr,Xr,zr,Zr,Kr,qr,Jr,Qr,$r,tn,en,rn,nn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,En,Cn,Tn,bn;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Ir||(Ir={}));class Sn{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(br(Sn,xr,!1,"f",Ar),!1):(br(Sn,xr,!0,"f",Ar),!0)}get disposed(){return Tr(this,Fr,"f")}constructor(){Rr.set(this,Ir.RGBA),Or.set(this,null),Dr.set(this,null),Lr.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Mr.set(this,null),Fr.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==Tr(Sn,xr,"f",Ar)&&Sn.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!Tr(Sn,xr,"f",Ar))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Sn._onLog&&(o=Date.now(),Sn._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=Ir.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Tr(Sn,xr,"f",Ar)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Sn._onLog&&Sn._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);br(this,Dr,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),br(this,Lr,e(t),"f"),br(this,Or,i(t),"f"),br(this,Rr,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Ir.GREY,Ir.GREY32].includes(p)?1:0);let m,_,v=Sr.translate(Sr.identity(),-1,-1);v=Sr.scale(v,2,2),v=Sr.scale(v,1/t.canvas.width,1/t.canvas.height),m=Sr.translate(v,u,d),m=Sr.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Sr.translate(Sr.identity(),a/i,h/r),_=Sr.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Tr(this,Or,"f"),e),v(t,Tr(this,Dr,"f"),Tr(this,Lr,"f"),Tr(this,Or,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Sn._onLog&&Sn._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Sn._onLog&&Sn._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===Ir.GREY?Ir.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Sn._onLog&&Sn._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Sn._onLog&&(n=Date.now(),Sn._onLog("transformPixelFormat(), START: "+n)),e===i)return Sn._onLog&&Sn._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[Ir.RGBA,Ir.RBGA,Ir.GRBA,Ir.GBRA,Ir.BRGA,Ir.BGRA];if(o.includes(e))if(i===Ir.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Sn._onLog&&(s=Date.now(),Sn._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=Ir.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),Tr(Sn,xr,"f",Ar)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Sn._onLog&&Sn._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===Ir.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{this.disposed||n.apply(i.target,r)}),0);else try{s=n.apply(i.target,r)}catch(t){}if(!0===s)break}}}dispose(){pr(this,kr,!0,"f")}}Pr=new WeakMap,kr=new WeakMap;const xn=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class An{static get version(){return"2.0.7"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Cr.OS))return An.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Cr.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),r(t)},l=t=>{s&&clearTimeout(s),o(),n(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{t.src&&await t.load(),await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a){await m;try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let r;try{r=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==r||r.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!mr(this,qr,"f"))return"closed";if("pending"===mr(this,qr,"f"))return"opening";if("fulfilled"===mr(this,qr,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?An.isStorageAvailable("localStorage")?pr(this,Xr,!0,"f"):(pr(this,Xr,!1,"f"),console.warn("Local storage is unavailable")):pr(this,Xr,!1,"f")}get ifSaveLastUsedCamera(){return mr(this,Xr,"f")}get isVideoPlaying(){return!(!mr(this,Ur,"f")||mr(this,Ur,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,r;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=mr(this,rn,"f"))||void 0===e||e.removeEventListener("click",mr(this,en,"f")),null===(i=mr(this,rn,"f"))||void 0===i||i.removeEventListener("touchend",mr(this,en,"f")),null===(r=mr(this,rn,"f"))||void 0===r||r.removeEventListener("touchmove",mr(this,tn,"f")),pr(this,rn,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Cr.OS)?(t.addEventListener("touchend",mr(this,en,"f")),t.addEventListener("touchmove",mr(this,tn,"f"))):t.addEventListener("click",mr(this,en,"f")))}get tapFocusEventBoundEl(){return mr(this,rn,"f")}get disposed(){return mr(this,dn,"f")}constructor(t){var e,i;Nr.add(this),Ur.set(this,null),jr.set(this,void 0),Gr.set(this,(()=>{"opened"===this.state&&mr(this,an,"f").fire("resumed",null,{target:this,async:!1})})),Wr.set(this,(()=>{mr(this,an,"f").fire("paused",null,{target:this,async:!1})})),Vr.set(this,void 0),Yr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Hr.set(this,void 0),Xr.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,zr.set(this,void 0),Zr.set(this,!0),Kr.set(this,void 0),qr.set(this,void 0),Jr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},Qr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,r;const n=window.getComputedStyle(mr(this,Ur,"f")).objectFit,s=this.getResolution(),o=mr(this,Ur,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=mr(this,Ur,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===n)d>u?(f=l/s.width,i=(t-a)/f,r=(e-h-(c-l/d)/2)/f):(f=c/s.height,r=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==n)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,r=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,r=(e-h+(l/d-c)/2)/f)}return{x:i,y:r}},$r.set(this,!1),tn.set(this,(()=>{pr(this,$r,!0,"f")})),en.set(this,(async t=>{var e;if(mr(this,$r,"f"))return void pr(this,$r,!1,"f");if(!mr(this,Qr,"f"))return;if(!this.isVideoPlaying)return;if(!mr(this,jr,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,r;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,r=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,r=t.changedTouches[0].clientY}const n=this.getResolution(),s=2*Math.round(Math.min(n.width,n.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,r)}catch(t){}if(o.x<0||o.x>n.width||o.y<0||o.y>n.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;An._onLog&&(c=Date.now());try{await mr(this,Nr,"m",Cn).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(An._onLog)throw An._onLog(t),t}An._onLog&&An._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;An._onLog&&An._onLog("Back to continuous focus."),null===(t=mr(this,jr,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),mr(this,an,"f").fire("tapfocus",null,{target:this,async:!1})})),rn.set(this,null),nn.set(this,1),sn.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!mr(this,Ur,"f"))return;const t=mr(this,nn,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)mr(this,Ur,"f").style.transform="";else{const e=window.getComputedStyle(mr(this,Ur,"f")).objectFit,i=mr(this,Ur,"f").videoWidth,r=mr(this,Ur,"f").videoHeight,{width:n,height:s}=mr(this,Ur,"f").getBoundingClientRect();if(n<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=n/s,a=i/r;let h=1;"contain"===e?h=oo?s/(i/t):n/(r/t));const l=h*(1-1/t)*(i/2-mr(this,sn,"f").x),c=h*(1-1/t)*(r/2-mr(this,sn,"f").y);mr(this,Ur,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},on.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Ir.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(An._onLog&&An._onLog("document visible. video paused: "+(null===(t=mr(this,Ur,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){An._onLog&&An._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){An._onLog&&An._onLog("document visible. 1st resume video failed, try open instead.")}e||await mr(this,Nr,"m",_n).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){An._onLog&&An._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){An._onLog&&An._onLog("document visible. 2rd resume video failed, try open instead.")}e||await mr(this,Nr,"m",_n).call(this)}}}else"hidden"===document.visibilityState&&(An._onLog&&An._onLog("document hidden. video paused: "+(null===(e=mr(this,Ur,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),dn.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{An.onWarning&&An.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),pr(this,an,new In,"f"),this.imageDataGetter=new Sn,document.addEventListener("visibilitychange",mr(this,un,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",mr(this,Gr,"f")),t.addEventListener("pause",mr(this,Wr,"f")),pr(this,Ur,t,"f")}getVideoEl(){return mr(this,Ur,"f")}releaseVideoEl(){var t,e;null===(t=mr(this,Ur,"f"))||void 0===t||t.removeEventListener("play",mr(this,Gr,"f")),null===(e=mr(this,Ur,"f"))||void 0===e||e.removeEventListener("pause",mr(this,Wr,"f")),pr(this,Ur,null,"f")}isVideoLoaded(){return!!mr(this,Ur,"f")&&4==mr(this,Ur,"f").readyState}async open(){if(mr(this,Kr,"f")&&!mr(this,Zr,"f")){if("pending"===mr(this,qr,"f"))return mr(this,Kr,"f");if("fulfilled"===mr(this,qr,"f"))return}mr(this,an,"f").fire("before:open",null,{target:this}),await mr(this,Nr,"m",_n).call(this),mr(this,an,"f").fire("played",null,{target:this,async:!1}),mr(this,an,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;mr(this,an,"f").fire("before:close",null,{target:this});const t=mr(this,Kr,"f");if(mr(this,Nr,"m",yn).call(this),t&&"pending"===mr(this,qr,"f")){try{await t}catch(t){}if(!1===mr(this,Zr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}pr(this,Kr,null,"f"),pr(this,qr,null,"f"),mr(this,an,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");mr(this,Ur,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await mr(this,Ur,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof mr(this,Vr,"f").video&&(mr(this,Vr,"f").video={}),delete mr(this,Vr,"f").video.facingMode,mr(this,Vr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&mr(this,Zr,"f"))){mr(this,an,"f").fire("before:camera:change",[],{target:this,async:!1}),await mr(this,Nr,"m",vn).call(this);try{this.resetSoftwareScale()}catch(t){}return mr(this,Yr,"f")}}async switchToFrontCamera(t){if("object"!=typeof mr(this,Vr,"f").video&&(mr(this,Vr,"f").video={}),(null==t?void 0:t.resolution)&&(mr(this,Vr,"f").video.width={ideal:t.resolution.width},mr(this,Vr,"f").video.height={ideal:t.resolution.height}),delete mr(this,Vr,"f").video.deviceId,mr(this,Vr,"f").video.facingMode={exact:"user"},pr(this,Hr,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&mr(this,Zr,"f"))){mr(this,an,"f").fire("before:camera:change",[],{target:this,async:!1}),mr(this,Nr,"m",vn).call(this);try{this.resetSoftwareScale()}catch(t){}return mr(this,Yr,"f")}}getCamera(){var t;if(mr(this,Yr,"f"))return mr(this,Yr,"f");{let e=(null===(t=mr(this,Vr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else r=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const n=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof mr(this,Vr,"f").video&&(mr(this,Vr,"f").video={}),i?(mr(this,Vr,"f").video.width={exact:t},mr(this,Vr,"f").video.height={exact:e}):(mr(this,Vr,"f").video.width={ideal:t},mr(this,Vr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&mr(this,Zr,"f"))return null;mr(this,an,"f").fire("before:resolution:change",[],{target:this,async:!1}),await mr(this,Nr,"m",vn).call(this);try{this.resetSoftwareScale()}catch(t){}const r=this.getResolution();return{width:r.width,height:r.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&mr(this,Ur,"f"))return{width:mr(this,Ur,"f").videoWidth,height:mr(this,Ur,"f").videoHeight};if(mr(this,jr,"f")){const t=mr(this,jr,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:mr(this,Ur,"f").videoWidth,height:mr(this,Ur,"f").videoHeight};{const t={width:0,height:0};let e=mr(this,Vr,"f").video.width||0,i=mr(this,Vr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,r,n,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=mr(this,ln,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=mr(this,Yr,"f"))||void 0===u?void 0:u.deviceId;let e=mr(this,ln,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],mr(this,ln,"f").set(d,e),pr(this,Jr,!0,"f");try{for(let t of this.detectedResolutions){await mr(this,jr,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),mr(this,Nr,"m",gn).call(this);const i=mr(this,jr,"f").getSettings(),r={width:i.width,height:i.height};f(d,r)||e.push({width:r.width,height:r.height})}}catch(t){throw mr(this,Nr,"m",yn).call(this),pr(this,Jr,!1,"f"),t}try{await mr(this,Nr,"m",_n).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{pr(this,Jr,!1,"f")}return e}{const e=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};let i=(null===(s=null===(n=null===(r=mr(this,Vr,"f"))||void 0===r?void 0:r.video)||void 0===n?void 0:n.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=mr(this,Vr,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=mr(this,Vr,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=mr(this,ln,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],mr(this,ln,"f").set(i,u);for(let t of this.detectedResolutions){const r=await e(i,t.width,t.height);r&&!f(i,r)&&u.push({width:r.width,height:r.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");pr(this,Vr,JSON.parse(JSON.stringify(t)),"f"),pr(this,Hr,null,"f"),e&&mr(this,Nr,"m",vn).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(mr(this,Vr,"f")))}resetMediaStreamConstraints(){pr(this,Vr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return mr(this,jr,"f").getCapabilities?mr(this,jr,"f").getCapabilities():{}}getCameraSettings(){if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return mr(this,jr,"f").getSettings()}async turnOnTorch(){if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await mr(this,jr,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await mr(this,jr,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=xn(t,r.min,r.step,r.max)),await mr(this,jr,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=xn(t,r.min,r.step,r.max)),await mr(this,jr,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!r)throw Error("Not supported.");e&&(tr.max&&(t=r.max));const n=this.getResolution();return await mr(this,jr,"f").applyConstraints({width:{ideal:Math.max(n.width,n.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),r=null==i?void 0:i.focusMode,n=null==i?void 0:i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!n)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(in.max&&(i=n.max),i=xn(i,n.min,n.step,n.max)),this._focusParameters.focusArea=null,await mr(this,jr,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await mr(this,Nr,"m",Cn).call(this,e,i,r)}}}else this._focusParameters.focusArea=null,await mr(this,jr,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){pr(this,Qr,!0,"f")}disableTapToFocus(){pr(this,Qr,!1,"f")}isTapToFocusEnabled(){return mr(this,Qr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?mr(this,Nr,"m",Tn).call(this,t.centerPoint):this.resetScaleCenter();try{if(mr(this,Nr,"m",bn).call(this,mr(this,sn,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*mr(this,nn,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!mr(this,jr,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const r=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!r)throw Error("Not supported.");return e&&(tr.max&&(t=r.max),t=xn(t,r.min,r.step,r.max)),await mr(this,jr,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&mr(this,Nr,"m",Tn).call(this,e),pr(this,nn,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return mr(this,nn,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();pr(this,sn,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(mr(this,Jr,"f"))return null;const e=Date.now();An._onLog&&An._onLog("getFrameData() START: "+e);const i=mr(this,Ur,"f").videoWidth,r=mr(this,Ur,"f").videoHeight;let n={sx:0,sy:0,sWidth:i,sHeight:r,dWidth:i,dHeight:r};(null==t?void 0:t.position)&&(n=JSON.parse(JSON.stringify(t.position)));let s=Ir.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=mr(this,nn,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=mr(this,sn,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,n=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))n=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.scaleCenter.y)/100*r}if(isNaN(e)||isNaN(n))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(n)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==r)return null;1!==o&&(n.sWidth=Math.round(n.sWidth/o),n.sHeight=Math.round(n.sHeight/o),n.sx=Math.round((1-1/o)*a.x+n.sx/o),n.sy=Math.round((1-1/o)*a.y+n.sy/o));const l=this.imageDataGetter.getImageData(mr(this,Ur,"f"),i,r,n,{pixelFormat:s,bufferContainer:h});if(!l)return null;const c=Date.now();return An._onLog&&An._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:mr(this,on,"f")}}on(t,e){if(!mr(this,hn,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);mr(this,an,"f").on(t,e)}off(t,e){mr(this,an,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),mr(this,an,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",mr(this,un,"f")),pr(this,dn,!0,"f")}}var Rn,On,Dn,Ln,Mn,Fn,Pn,kn,Bn,Nn,Un,jn,Gn,Wn,Vn,Yn,Hn,Xn,zn,Zn,Kn,qn,Jn,Qn,$n,ts,es,is,rs,ns,ss,os,as;Ur=new WeakMap,jr=new WeakMap,Gr=new WeakMap,Wr=new WeakMap,Vr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,Zr=new WeakMap,Kr=new WeakMap,qr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,$r=new WeakMap,tn=new WeakMap,en=new WeakMap,rn=new WeakMap,nn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,Nr=new WeakSet,fn=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(mr(this,Hr,"f"))delete t.video.facingMode,t.video.deviceId={exact:mr(this,Hr,"f")};else if(this.ifSaveLastUsedCamera&&An.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Cr.OS)?(await this._getCameras(!1),mr(this,Nr,"m",gn).call(this),e=An.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Cr.OS)||(await this._getCameras(!1),mr(this,Nr,"m",gn).call(this),e=An.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const r=await e(i);r&&(delete t.video.facingMode,t.video.deviceId={exact:r})}return t},gn=function(){if(mr(this,Zr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},mn=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let r;try{An._onLog&&An._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const n=async t=>{for(let n of e){n&&(await new Promise((t=>setTimeout(t,n))),mr(this,Nr,"m",gn).call(this));try{An._onLog&&An._onLog("ask "+JSON.stringify(t)),r=await navigator.mediaDevices.getUserMedia(t),mr(this,Nr,"m",gn).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,An._onLog&&An._onLog(t.message||t)}}};if(await n(t),r||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await n(t)),!r&&t.video.facingMode&&(delete t.video.facingMode,await n(t)),r||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await n(t))),!r)throw i;return r}catch(t){throw null==r||r.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},pn=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),pr(this,jr,null,"f")},_n=async function(){pr(this,Zr,!1,"f");const t=pr(this,zr,Symbol(),"f");if(mr(this,Kr,"f")&&"pending"===mr(this,qr,"f")){try{await mr(this,Kr,"f")}catch(t){}mr(this,Nr,"m",gn).call(this)}if(t!==mr(this,zr,"f"))return;const e=pr(this,Kr,(async()=>{pr(this,qr,"pending","f");try{if(this.videoSrc){if(!mr(this,Ur,"f"))throw new Error("'videoEl' should be set.");await An.playVideo(mr(this,Ur,"f"),this.videoSrc,this.cameraOpenTimeout),mr(this,Nr,"m",gn).call(this)}else{let t=await mr(this,Nr,"m",fn).call(this);mr(this,Nr,"m",pn).call(this);let e=await mr(this,Nr,"m",mn).call(this,t);await this._getCameras(!1),mr(this,Nr,"m",gn).call(this);const i=()=>{const t=e.getVideoTracks();let i,r;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,r=e;break}}return r},r=mr(this,Vr,"f");if("object"==typeof r.video){let n=r.video.facingMode;if(n instanceof Array&&n.length&&(n=n[0]),"object"==typeof n&&(n=n.exact||n.ideal),!(mr(this,Hr,"f")||this.ifSaveLastUsedCamera&&An.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||r.video.deviceId)){const r=i(),s=An.findBestCamera(this._arrCameras,n,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==r?void 0:r.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await mr(this,Nr,"m",mn).call(this,t),mr(this,Nr,"m",gn).call(this))}}const n=i();(null==n?void 0:n.deviceId)&&(pr(this,Hr,n&&n.deviceId,"f"),this.ifSaveLastUsedCamera&&An.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",mr(this,Hr,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),mr(this,Ur,"f")&&(await An.playVideo(mr(this,Ur,"f"),e,this.cameraOpenTimeout),mr(this,Nr,"m",gn).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&pr(this,jr,s[0],"f"),pr(this,Yr,n,"f")}}catch(t){throw mr(this,Nr,"m",yn).call(this),pr(this,qr,null,"f"),t}pr(this,qr,"fulfilled","f")})(),"f");return e},vn=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=mr(this,Yr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await mr(this,Nr,"m",_n).call(this);const r=this.getResolution();e&&e!==mr(this,Yr,"f").deviceId&&mr(this,an,"f").fire("camera:changed",[mr(this,Yr,"f").deviceId,e],{target:this,async:!1}),i.width==r.width&&i.height==r.height||mr(this,an,"f").fire("resolution:changed",[{width:r.width,height:r.height},{width:i.width,height:i.height}],{target:this,async:!1}),mr(this,an,"f").fire("played",null,{target:this,async:!1})},yn=function(){mr(this,Nr,"m",pn).call(this),pr(this,Yr,null,"f"),mr(this,Ur,"f")&&(mr(this,Ur,"f").srcObject=null,this.videoSrc&&(mr(this,Ur,"f").pause(),mr(this,Ur,"f").currentTime=0)),pr(this,Zr,!0,"f");try{this.resetSoftwareScale()}catch(t){}},wn=async function t(e,i){const r=t=>{if(!mr(this,jr,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){mr(this,jr,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let n;i=xn(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await mr(this,jr,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),r(e),n=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,n)})),r(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();if(s>=l.width||o>=l.height)throw new Error("Invalid area.");s+a>l.width&&(a=l.width-s),o+h>l.height&&(h=l.height-o),s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(mr(this,Ur,"f"),l.width,l.height,{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:Ir.RGBA,bufferContainer:d}))return mr(this,Nr,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await mr(this,Nr,"m",t).call(this,e,o,a,n,s,c,u)}else{let h=await mr(this,Nr,"m",wn).call(this,e,c);if(a>h)return await mr(this,Nr,"m",t).call(this,e,o,a,n,s,c,h);if(a==h)return await mr(this,Nr,"m",t).call(this,e,o,a,c,h);let u=await mr(this,Nr,"m",wn).call(this,e,l);if(u>a&&ao.width||h<0||h>o.height)throw new Error("Invalid 'centerPoint'.");let l=0;if(e.endsWith("px"))l=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");l=parseFloat(e)/100*o.width}if(isNaN(l)||l<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*o.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==mr(this,nn,"f")){const t=mr(this,nn,"f"),e=mr(this,sn,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=xn(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=xn(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=xn(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await mr(this,Nr,"m",wn).call(this,t,s),a=await mr(this,Nr,"m",wn).call(this,t,n),h=await mr(this,Nr,"m",wn).call(this,t,r);if(a>h&&ho&&a>o){let e=await mr(this,Nr,"m",wn).call(this,t,i);const n=await mr(this,Nr,"m",En).call(this,t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await mr(this,Nr,"m",En).call(this,t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)},Tn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,r=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))r=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(r))throw new Error("Invalid scale center.");pr(this,sn,{x:i,y:r},"f")},bn=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},An.browserInfo=Cr,An.onWarning=null===(Br=null===window||void 0===window?void 0:window.console)||void 0===Br?void 0:Br.warn;class hs{constructor(t){Rn.add(this),On.set(this,void 0),Dn.set(this,0),Ln.set(this,void 0),Mn.set(this,0),Fn.set(this,!1),Ee(this,On,t,"f")}startCharging(){we(this,Fn,"f")||(hs._onLog&&hs._onLog("start charging."),we(this,Rn,"m",kn).call(this),Ee(this,Fn,!0,"f"))}stopCharging(){we(this,Ln,"f")&&clearTimeout(we(this,Ln,"f")),we(this,Fn,"f")&&(hs._onLog&&hs._onLog("stop charging."),Ee(this,Dn,Date.now()-we(this,Mn,"f"),"f"),Ee(this,Fn,!1,"f"))}}On=new WeakMap,Dn=new WeakMap,Ln=new WeakMap,Mn=new WeakMap,Fn=new WeakMap,Rn=new WeakSet,Pn=function(){ut.cfd(1),hs._onLog&&hs._onLog("charge 1.")},kn=function t(){0==we(this,Dn,"f")&&we(this,Rn,"m",Pn).call(this),Ee(this,Mn,Date.now(),"f"),we(this,Ln,"f")&&clearTimeout(we(this,Ln,"f")),Ee(this,Ln,setTimeout((()=>{Ee(this,Dn,0,"f"),we(this,Rn,"m",t).call(this)}),we(this,On,"f")-we(this,Dn,"f")),"f")};const ls=new Map([[n.IPF_GRAYSCALED,Ir.GREY],[n.IPF_ABGR_8888,Ir.RGBA],[n.IPF_ARGB_8888,Ir.BGRA]]),cs=new Map([[Ir.GREY,n.IPF_GRAYSCALED],[Ir.RGBA,n.IPF_ABGR_8888],[Ir.BGRA,n.IPF_ARGB_8888]]),us="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class ds extends L{static set _onLog(t){Ee(ds,Nn,t,"f",Un),An._onLog=t,hs._onLog=t}static get _onLog(){return we(ds,Nn,"f",Un)}static async detectEnvironment(){return await(async()=>({wasm:Ce,worker:Te,getUserMedia:be,camera:await Se(),browser:ve.browser,version:ve.version,OS:ve.OS}))()}static async testCameraAccess(){const t=await An.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof gr))throw new TypeError("Invalid view.");if(null===(e=ot.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ot.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await ut.loadWasm(["license"]),await ot.license.dynamsoft()}const r=new ds(t);return ds.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ds.onWarning&&ds.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ds.onWarning&&ds.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),r}get video(){return we(this,jn,"f").getVideoEl()}set videoSrc(t){if(!we(this,jn,"f"))throw new Error("Camera manager is null.");we(this,Gn,"f")&&(we(this,Gn,"f")._hideDefaultSelection=!0),we(this,jn,"f").videoSrc=t}get videoSrc(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!we(this,jn,"f"))throw new Error("Camera manager is null.");we(this,jn,"f").ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!we(this,jn,"f"))throw new Error("Camera manager is null.");we(this,jn,"f").ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!we(this,jn,"f"))throw new Error("Camera manager is null.");we(this,jn,"f").cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ee(this,Hn,t,"f")}get singleFrameMode(){return we(this,Hn,"f")}get _isFetchingStarted(){return we(this,Jn,"f")}get disposed(){return we(this,is,"f")}constructor(t){if(super(),Bn.add(this),jn.set(this,void 0),Gn.set(this,void 0),Wn.set(this,"closed"),Vn.set(this,void 0),Yn.set(this,!1),Hn.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&we(this,Gn,"f")&&!we(this,Gn,"f").disposed&&await this.selectCamera(we(this,Gn,"f")._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!we(this,Gn,"f")||we(this,Gn,"f").disposed)return;let t,e;if(we(this,Gn,"f")._selRsl&&-1!=we(this,Gn,"f")._selRsl.selectedIndex){let i=we(this,Gn,"f")._selRsl.options[we(this,Gn,"f")._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&we(this,Gn,"f")&&!we(this,Gn,"f").disposed&&this.close()},Xn.set(this,((t,e,i,r)=>{const n=Date.now(),s={sx:r.x,sy:r.y,sWidth:r.width,sHeight:r.height,dWidth:r.width,dHeight:r.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=we(this,jn,"f").imageDataGetter.getImageData(t,e,i,s,{pixelFormat:ls.get(this.getPixelFormat())});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===Ir.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:cs.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:_t.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-n,timeStamp:t},toCanvas:we(this,zn,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=we(this,Gn,"f")?we(this,Gn,"f").getConvertedRegion():ti.convert(we(this,Kn,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=we(this,Xn,"f").call(this,t,t.width,t.height,e);we(this,Vn,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},zn.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===n.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=we(this,jn,"f").getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");we(this,Gn,"f")&&!we(this,Gn,"f").disposed?(this.video.style.transform=1===t?"":`scale(${t})`,we(this,Gn,"f")._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ve.OS)?we(this,jn,"f").setResolution(1280,720):we(this,jn,"f").setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&this.setCameraView(t),this._on("before:camera:change",(()=>{we(this,es,"f").stopCharging();const t=we(this,Gn,"f");t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=we(this,Gn,"f");t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{we(this,es,"f").stopCharging();const t=we(this,Gn,"f");t&&t.disposed})),this._on("resumed",(()=>{const t=we(this,Gn,"f");t&&t.disposed})),this._on("tapfocus",(()=>{we(this,$n,"f").tapToFocus&&we(this,es,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,r,n,s;if(we(this,Bn,"m",rs).call(this)||!this.isOpen()||this.isPaused())return;const o=t.intermediateResultUnits;ds._onLog&&(ds._onLog("intermediateResultUnits:"),ds._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===wt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===wt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(ds._onLog&&(ds._onLog("hasLocalizedBarcodes:"),ds._onLog(h)),we(this,$n,"f").autoZoom||we(this,$n,"f").enhancedFocus)if(a)we(this,ts,"f").autoZoomInFrameArray.length=0,we(this,ts,"f").autoZoomOutFrameCount=0,we(this,ts,"f").frameArrayInIdealZoom.length=0,we(this,ts,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),we(this,$n,"f").autoZoom&&we(this,es,"f").startCharging()},a=async t=>{await this.setFocus(t),we(this,$n,"f").enhancedFocus&&we(this,es,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(r=h.cropRegion)||void 0===r?void 0:r.top)||0,u=(null===(n=h.cropRegion)||void 0===n?void 0:n.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,r,n;{const t=this.video.videoWidth*(1-we(this,ts,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+we(this,ts,"f").autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-we(this,ts,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+we(this,ts,"f").autoZoomDetectionArea)/2;n=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:r,y:a}]}ds._onLog&&(ds._onLog("detectionArea:"),ds._onLog(n));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const n=t.length;if(n<=2)return!1;for(let s=0;s0!=si(a.y-i)>0&&si(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}(e,t.x,t.y)},r=(t,e)=>!!(oi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||oi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||oi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||oi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(r([e[0].x,e[0].y,e[1].x,e[1].y],t)||r([e[1].x,e[1].y,e[2].x,e[2].y],t)||r([e[2].x,e[2].y,e[3].x,e[3].y],t)||r([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===wt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{gr._transformCoordinates(t,l,c,u,d,f,g)})),t(n,e)&&s.push(i)}if(ds._debug&&we(this,Gn,"f")){const t=this.__layer||(this.__layer=we(this,Gn,"f")._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=ar.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===wt.IRUT_LOCALIZED_BARCODES)for(let r of i.localizedBarcodes){if(!r)continue;const i=r.location.points,n=new vi({points:i},e);t.addDrawingItems([n])}}}if(ds._onLog&&(ds._onLog("intersectedResults:"),ds._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter((t=>t.possibleFormats==us.BF_QR_CODE||t.possibleFormats==us.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==us.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,r=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(r-g/2)*(r-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let r=1;r1.1*a.confidence||t[r].confidence>.9*a.confidence&&ni&&s>i&&o>i&&h>i&&m.result.moduleSize{})),we(this,ts,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=we(this,ts,"f").autoZoomInFrameLimit[1]){we(this,ts,"f").autoZoomInFrameArray.length=0;const i=[(.5-r)/(.5-n),(.5-r)/(.5-s),(.5-r)/(.5-o),(.5-r)/(.5-h)].filter((t=>t>0)),a=Math.min(...i,we(this,ts,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/we(this,ts,"f").autoZoomInMaxTimes),we(this,ts,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(we(this,ts,"f").minValue,u),u=Math.min(we(this,ts,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(we(this,ts,"f").autoZoomInFrameArray.length=0,we(this,ts,"f").frameArrayInIdealZoom.push(!0),we(this,ts,"f").frameArrayInIdealZoom.splice(0,we(this,ts,"f").frameArrayInIdealZoom.length-we(this,ts,"f").frameLimitInIdealZoom[0]),we(this,ts,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=we(this,ts,"f").frameLimitInIdealZoom[1]&&(we(this,ts,"f").frameArrayInIdealZoom.length=0,we(this,$n,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!we(this,$n,"f").autoZoom&&we(this,$n,"f").enhancedFocus&&(we(this,ts,"f").autoFocusFrameArray.push(!0),we(this,ts,"f").autoFocusFrameArray.splice(0,we(this,ts,"f").autoFocusFrameArray.length-we(this,ts,"f").autoFocusFrameLimit[0]),we(this,ts,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=we(this,ts,"f").autoFocusFrameLimit[1])){we(this,ts,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(we(this,$n,"f").autoZoom){if(we(this,ts,"f").autoZoomInFrameArray.push(!1),we(this,ts,"f").autoZoomInFrameArray.splice(0,we(this,ts,"f").autoZoomInFrameArray.length-we(this,ts,"f").autoZoomInFrameLimit[0]),we(this,ts,"f").autoZoomOutFrameCount++,we(this,ts,"f").frameArrayInIdealZoom.push(!1),we(this,ts,"f").frameArrayInIdealZoom.splice(0,we(this,ts,"f").frameArrayInIdealZoom.length-we(this,ts,"f").frameLimitInIdealZoom[0]),we(this,ts,"f").autoZoomOutFrameCount>=we(this,ts,"f").autoZoomOutFrameLimit){we(this,ts,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let r=i-Math.max((i-1)*we(this,ts,"f").autoZoomOutStepRate,we(this,ts,"f").autoZoomOutMinStep);r=Math.max(we(this,ts,"f").minValue,r),r=Math.min(we(this,ts,"f").maxValue,r);try{await e({factor:r})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}we(this,$n,"f").enhancedFocus&&a({mode:"continuous"}).catch((()=>{}))}!we(this,$n,"f").autoZoom&&we(this,$n,"f").enhancedFocus&&(we(this,ts,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch((()=>{})))}}},Ee(this,es,new hs(1e4),"f")}setCameraView(t){if(!(t instanceof gr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(we(this,Gn,"f")._hideDefaultSelection=!0),we(this,Bn,"m",rs).call(this)||we(this,jn,"f").setVideoEl(t.getVideoElement()),Ee(this,Gn,t,"f"),this.addListenerToView()}getCameraView(){return we(this,Gn,"f")}releaseCameraView(){we(this,Gn,"f")&&(this.removeListenerFromView(),we(this,Gn,"f").disposed||(we(this,Gn,"f")._singleFrameMode="disabled",we(this,Gn,"f")._onSingleFrameAcquired=null,we(this,Gn,"f")._hideDefaultSelection=!1),we(this,jn,"f").releaseVideoEl(),Ee(this,Gn,null,"f"))}addListenerToView(){if(!we(this,Gn,"f"))return;if(we(this,Gn,"f").disposed)throw new Error("'cameraView' has been disposed.");const t=we(this,Gn,"f");we(this,Bn,"m",rs).call(this)||this.videoSrc||(t._innerComponent&&(we(this,jn,"f").tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!we(this,Gn,"f")||we(this,Gn,"f").disposed)return;const t=we(this,Gn,"f");we(this,jn,"f").tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return we(this,Bn,"m",rs).call(this)?we(this,Wn,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(we(this,jn,"f").state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=we(this,Gn,"f");if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,we(this,Bn,"m",rs).call(this)?t._clickIptSingleFrameMode():(we(this,jn,"f").setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(we(this,Bn,"m",rs).call(this));else{try{await we(this,jn,"f").open()}catch(e){throw t&&t._stopLoading(),e}we(this,Yn,"f")&&this.turnOnTorch().catch((()=>{}));const i=this.getResolution();e.width=i.width,e.height=i.height,e.deviceId=this.getSelectedCamera().deviceId}return Ee(this,Wn,"open","f"),t&&(t._innerComponent.style.display="",we(this,Bn,"m",rs).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),we(this,jn,"f")._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),we(this,Vn,"f").fire("opened",null,{target:this,async:!1}),e}close(){const t=we(this,Gn,"f");if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");this.stopFetching(),this.clearBuffer(),we(this,Bn,"m",rs).call(this)||we(this,jn,"f").close(),Ee(this,Wn,"closed","f"),we(this,es,"f").stopCharging(),t&&(t._innerComponent.style.display="none",we(this,Bn,"m",rs).call(this)&&t._innerComponent.removeElement("content"),t._stopLoading()),we(this,Vn,"f").fire("closed",null,{target:this,async:!1})}pause(){if(we(this,Bn,"m",rs).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");we(this,jn,"f").pause()}isPaused(){var t;return!we(this,Bn,"m",rs).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(we(this,Bn,"m",rs).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await we(this,jn,"f").resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await we(this,jn,"f").setCamera(e),Ee(this,Yn,!1,"f");const i=this.getResolution(),r=we(this,Gn,"f");return r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),we(this,jn,"f")._arrCameras),r._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return we(this,jn,"f").getCamera()}async getAllCameras(){return we(this,jn,"f").getCameras()}async setResolution(t){await we(this,jn,"f").setResolution(t.width,t.height),we(this,Yn,"f")&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=we(this,Gn,"f");return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return we(this,jn,"f").getResolution()}getAvailableResolutions(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?we(this,Vn,"f").on(t,e):we(this,jn,"f").on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?we(this,Vn,"f").off(t,e):we(this,jn,"f").off(t,e)}on(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._on(r,e)}off(t,e){const i=t.toLowerCase(),r=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!r)throw new Error("Invalid event.");this._off(r,e)}getVideoSettings(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=we(this,jn,"f"))||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return we(this,jn,"f").getCameraSettings()}async turnOnTorch(){var t;if(we(this,Bn,"m",rs).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");await(null===(t=we(this,jn,"f"))||void 0===t?void 0:t.turnOnTorch()),Ee(this,Yn,!0,"f")}async turnOffTorch(){var t;if(we(this,Bn,"m",rs).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=we(this,jn,"f"))||void 0===t?void 0:t.turnOffTorch()),Ee(this,Yn,!1,"f")}async setColorTemperature(t){if(we(this,Bn,"m",rs).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await we(this,jn,"f").setColorTemperature(t,!0)}getColorTemperature(){return we(this,jn,"f").getColorTemperature()}async setExposureCompensation(t){var e;if(we(this,Bn,"m",rs).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=we(this,jn,"f"))||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e;if(we(this,Bn,"m",rs).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=we(this,jn,"f"))||void 0===e?void 0:e.setZoom(t))}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(we(this,Bn,"m",rs).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=we(this,jn,"f"))||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(we(this,Bn,"m",rs).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=we(this,jn,"f"))||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(we(this,Bn,"m",rs).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=we(this,jn,"f"))||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=we(this,jn,"f"))||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){we(this,ts,"f").minValue=t.min,we(this,ts,"f").maxValue=t.max}getAutoZoomRange(){return{min:we(this,ts,"f").minValue,max:we(this,ts,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ot.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==ut.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&Le.EF_ENHANCED_FOCUS&&(we(this,$n,"f").enhancedFocus=!0),t&Le.EF_AUTO_ZOOM&&(we(this,$n,"f").autoZoom=!0),t&Le.EF_TAP_TO_FOCUS&&(we(this,$n,"f").tapToFocus=!0,we(this,jn,"f").enableTapToFocus())}disableEnhancedFeatures(t){t&Le.EF_ENHANCED_FOCUS&&(we(this,$n,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&Le.EF_AUTO_ZOOM&&(we(this,$n,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&Le.EF_TAP_TO_FOCUS&&(we(this,$n,"f").tapToFocus=!1,we(this,jn,"f").disableTapToFocus()),we(this,Bn,"m",ss).call(this)&&we(this,Bn,"m",ns).call(this)||we(this,es,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!ze(t)&&!Qe(t))throw TypeError("Invalid 'region'.");Ee(this,Kn,t?JSON.parse(JSON.stringify(t)):null,"f"),we(this,Gn,"f")&&!we(this,Gn,"f").disposed&&we(this,Gn,"f").setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),we(this,Gn,"f")&&!we(this,Gn,"f").disposed&&(null===t?we(this,Gn,"f").setScanRegionMaskVisible(!1):we(this,Gn,"f").setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(we(this,Kn,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ee(this,Zn,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!we(this,jn,"f").isVideoLoaded()||we(this,Bn,"m",rs).call(this))}startFetching(){if(we(this,Bn,"m",rs).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");we(this,Jn,"f")||(Ee(this,Jn,!0,"f"),we(this,Bn,"m",os).call(this))}stopFetching(){we(this,Jn,"f")&&(ds._onLog&&ds._onLog("DCE: stop fetching loop: "+Date.now()),we(this,Qn,"f")&&clearTimeout(we(this,Qn,"f")),Ee(this,Jn,!1,"f"))}fetchImage(){if(we(this,Bn,"m",rs).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=ti.convert(we(this,Kn,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},r=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const n=we(this,jn,"f").getFrameData({position:i,pixelFormat:ls.get(this.getPixelFormat())});if(!n)return null;let s;s=n.pixelFormat===Ir.GREY?n.width:4*n.width;let o=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(o=!1),{bytes:n.data,width:n.width,height:n.height,stride:s,format:cs.get(n.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:_t.ITT_VIDEO_FRAME,isCropped:o,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:n.width,currentHeight:n.height,timeSpent:n.timeSpent,timeStamp:n.timeStamp},toCanvas:we(this,zn,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,we(this,Jn,"f")&&(we(this,Qn,"f")&&clearTimeout(we(this,Qn,"f")),Ee(this,Qn,setTimeout((()=>{this.disposed||we(this,Bn,"m",os).call(this)}),t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ee(this,qn,t,"f")}getPixelFormat(){return we(this,qn,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(we(this,Bn,"m",rs).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],r=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),n=new Image;n.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),t(n)},n.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),n=r instanceof HTMLImageElement?r.naturalWidth:r.width,s=r instanceof HTMLImageElement?r.naturalHeight:r.height;let o=ti.convert(we(this,Kn,"f"),n,s);o||(o={x:0,y:0,width:n,height:s});const a=we(this,Xn,"f").call(this,r,n,s,o);t&&t(a)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=we(this,Bn,"m",as).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=we(this,Bn,"m",as).call(this,t);return{x:e.clientX,y:e.clientY}}dispose(){this.close(),we(this,jn,"f").dispose(),this.releaseCameraView(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}function fs(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}function gs(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?n.call(t,i):n?n.value=i:e.set(t,i),i}Nn=ds,jn=new WeakMap,Gn=new WeakMap,Wn=new WeakMap,Vn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,Zn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,Bn=new WeakSet,rs=function(){return"disabled"!==this.singleFrameMode},ns=function(){return!this.videoSrc&&"opened"===we(this,jn,"f").state},ss=function(){for(let t in we(this,$n,"f"))if(1==we(this,$n,"f")[t])return!0;return!1},os=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!we(this,Jn,"f"))return we(this,Qn,"f")&&clearTimeout(we(this,Qn,"f")),void Ee(this,Qn,setTimeout((()=>{this.disposed||we(this,Bn,"m",t).call(this)}),this.fetchInterval),"f");const e=()=>{var t;let e;ds._onLog&&ds._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=we(this,Zn,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=we(this,Zn,"f"))||void 0===t||t.onErrorReceived(gt.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),ds._onLog&&ds._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),we(this,Vn,"f").fire("frameAddedToBuffer",null,{async:!1})):ds._onLog&&ds._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case i.BOPM_BLOCK:break;case i.BOPM_UPDATE:e()}else e();we(this,Qn,"f")&&clearTimeout(we(this,Qn,"f")),Ee(this,Qn,setTimeout((()=>{this.disposed||we(this,Bn,"m",t).call(this)}),this.fetchInterval),"f")},as=function(t){if(!we(this,Gn,"f"))throw new Error("Camera view is not set.");if(we(this,Gn,"f").disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!we(this,Bn,"m",rs).call(this)&&!we(this,jn,"f").isVideoLoaded())throw new Error("Video is not loaded.");if(we(this,Bn,"m",rs).call(this)&&!we(this,Gn,"f")._cvsSingleFrameMode)throw new Error("No image is selected.");const e=we(this,Gn,"f")._innerComponent.getBoundingClientRect(),i=e.left,r=e.top,n=i+window.scrollX,s=r+window.scrollY,{width:o,height:a}=we(this,Gn,"f")._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(we(this,Bn,"m",rs).call(this)){const t=we(this,Gn,"f")._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=we(this,Gn,"f").getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)ut+e*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return ms.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return ms.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return ms.multiply(t,[e,0,0,0,i,0,0,0,1])}}var ps,_s,vs,ys,ws,Es,Cs,Ts,bs,Ss,Is,xs,As,Rs,Os,Ds,Ls,Ms,Fs,Ps,ks,Bs,Ns;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(ps||(ps={}));class Us{static get version(){return"1.1.0"}static checkWebGLSupport(){return null===document.createElement("canvas").getContext("webgl")?(gs(Us,_s,!1,"f",vs),!1):(gs(Us,_s,!0,"f",vs),!0)}get disposed(){return fs(this,bs,"f")}constructor(){ys.set(this,ps.RGBA),ws.set(this,null),Es.set(this,null),Cs.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Ts.set(this,null),bs.set(this,!1)}drawImage(t,e,i,r,n,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!r)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if(null==fs(Us,_s,"f",vs)&&Us.checkWebGLSupport(),(null==s?void 0:s.bUseWebGL)&&!fs(Us,_s,"f",vs))throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;Us._onLog&&(o=Date.now(),Us._onLog("drawImage(), START: "+o));let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;n&&(n.sx&&(a=Math.round(n.sx)),n.sy&&(h=Math.round(n.sy)),n.sWidth&&(l=Math.round(n.sWidth)),n.sHeight&&(c=Math.round(n.sHeight)),n.dx&&(u=Math.round(n.dx)),n.dy&&(d=Math.round(n.dy)),n.dWidth&&(f=Math.round(n.dWidth)),n.dHeight&&(g=Math.round(n.dHeight)));let m,p=ps.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!fs(Us,_s,"f",vs)||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Us._onLog&&Us._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},n=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n \n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n \n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n \n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[n(t,t.VERTEX_SHADER,s),n(t,t.FRAGMENT_SHADER,a)]);gs(this,Es,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),gs(this,Cs,e(t),"f"),gs(this,ws,i(t),"f"),gs(this,ys,p,"f")}const n=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const r=t.RGBA,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[ps.GREY,ps.GREY32].includes(p)?1:0);let m,_,v=ms.translate(ms.identity(),-1,-1);v=ms.scale(v,2,2),v=ms.scale(v,1/t.canvas.width,1/t.canvas.height),m=ms.translate(v,u,d),m=ms.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=ms.translate(ms.identity(),a/i,h/r),_=ms.scale(_,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,fs(this,ws,"f"),e),v(t,fs(this,Es,"f"),fs(this,Cs,"f"),fs(this,ws,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Us._onLog&&Us._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Us._onLog&&Us._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===ps.GREY?ps.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Us._onLog&&Us._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,r,n,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let r,n=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(n=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),r=new Uint8Array(i.buffer,0,4*o*a)):(r=new Uint8Array(4*o*a),e.readPixels(n,s,o,a,e.RGBA,e.UNSIGNED_BYTE,r))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(n,s,o,a),r=new Uint8Array(e.data.buffer),null==i||i.set(r)}return r}transformPixelFormat(t,e,i,r){let n,s;if(Us._onLog&&(n=Date.now(),Us._onLog("transformPixelFormat(), START: "+n)),e===i)return Us._onLog&&Us._onLog("transformPixelFormat() end. Costs: "+(Date.now()-n)),r?new Uint8Array(t):t;const o=[ps.RGBA,ps.RBGA,ps.GRBA,ps.GBRA,ps.BRGA,ps.BGRA];if(o.includes(e))if(i===ps.GREY){s=new Uint8Array(t.length/4);for(let e=0;ee||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let s;Us._onLog&&(s=Date.now(),Us._onLog("getImageData(), START: "+s));const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=ps.RGBA;(null==n?void 0:n.pixelFormat)&&(d=n.pixelFormat);let f,g,m,p=null;if((null==n?void 0:n.bufferContainer)&&(p=n.bufferContainer),fs(Us,_s,"f",vs)&&(this.useWebGLByDefault&&null==(null==n?void 0:n.bUseWebGL)||(null==n?void 0:n.bUseWebGL))){Us._onLog&&Us._onLog("getImageData() in WebGL."),this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs;try{if(p)if(d===ps.GREY){if(m=new Uint8Array(4*c*u),g=this.drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},{pixelFormat:d,bUseWebGL:!0,bufferContainer:m}),m=this.transformPixelFormat(m,g.pixelFormat,d),p){if(p.length{var e;if(!this.isUseMagnifier)return;if(we(this,Rs,"f")||Ee(this,Rs,new js,"f"),!we(this,Rs,"f").magnifierCanvas)return;document.body.contains(we(this,Rs,"f").magnifierCanvas)||(we(this,Rs,"f").magnifierCanvas.style.position="fixed",we(this,Rs,"f").magnifierCanvas.style.boxSizing="content-box",we(this,Rs,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(we(this,Rs,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void we(this,Ds,"f").call(this);const r=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!r)return;const n=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*n,o=[{image:i,width:i.width,height:i.height},{image:r,width:r.width,height:r.height}];we(this,Rs,"f").update(s,t.pointer,n,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(we(this,Rs,"f").magnifierCanvas.style.left="auto",we(this,Rs,"f").magnifierCanvas.style.top="0",we(this,Rs,"f").magnifierCanvas.style.right="0"):(we(this,Rs,"f").magnifierCanvas.style.left="0",we(this,Rs,"f").magnifierCanvas.style.top="0",we(this,Rs,"f").magnifierCanvas.style.right="auto")}we(this,Rs,"f").show()})),Ds.set(this,(()=>{we(this,Rs,"f")&&we(this,Rs,"f").hide()})),Ls.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if(e="string"==typeof t?await ai(t):t,e instanceof HTMLDivElement&&0==e.childElementCount){const t=we(this,xs,"m",Ms).call(this);this._setUIElement(t),e.append(this.getUIElement()),this.UIElement=e}else this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=new dr,e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let r=this._innerComponent.getElement("content");r||(r=document.createElement("canvas"),r.style.objectFit="contain",this._innerComponent.setElement("content",r)),r.width===e&&r.height===i||(r.width=e,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&n.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(Xe(t)){Ee(this,As,t,"f");const{width:e,height:i,bytes:r,format:s}=Object.assign({},t);let o;if(s===n.IPF_GRAYSCALED){o=new Uint8ClampedArray(e*i*4);for(let t=0;t{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{we(this,Fs,"f",Ns).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,we(this,Fs,"f",Ns).delete(t),we(this,Fs,"f",Bs).add(t)}))}else we(this,Fs,"f",ks)||(Ee(this,Fs,!0,"f",ks),console.warn("The requested audio tracks exceed 64 and will not be played."));t&&we(this,Fs,"f",Ns).add(t)}static vibrate(){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ws.vibrateDuration)}}Fs=Ws,Ps={value:"data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"},ks={value:!1},Bs={value:new Set},Ns={value:new Set},Ws.beepSoundSource=we(Ws,Fs,"f",Ps),Ws.vibrateDuration=300;const Vs="undefined"==typeof self,Ys=(()=>{if(!Vs&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),Hs=t=>{if(null==t&&(t="./"),Vs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};null==at.dbr&&(at.dbr=Ys),lt.dbr={js:!1,wasm:!0,deps:["license","dip"]},ot.dbr={};const Xs="1.2.0";"string"!=typeof at.std&&C(at.std.version,Xs)<0&&(at.std={version:Xs,path:Hs(Ys+`../../dynamsoft-capture-vision-std@${Xs}/dist/`)});const zs="2.2.10";(!at.dip||"string"!=typeof at.dip&&C(at.dip.version,zs)<0)&&(at.dip={version:zs,path:Hs(Ys+`../../dynamsoft-image-processing@${zs}/dist/`)});let Zs=class{static getVersion(){const t=st.dbr&&st.dbr.wasm;return`10.2.10(Worker: ${st.dbr&&st.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const Ks="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};var qs,Js,Qs,$s;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(qs||(qs={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Js||(Js={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP"}(Qs||(Qs={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP"}($s||($s={}));const to=async(t,e,i)=>await new Promise((async(r,n)=>{try{const n=e.split(".");let s=n[n.length-1];const o=await ro(`image/${s}`,t);n.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return r(a)}catch(t){return n()}})),eo=t=>{const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},io=(t,e)=>{const i=eo(e);let r=new Image,n=i.toDataURL(t);return r.src=n,r},ro=async(t,e)=>{const i=eo(e);return new Promise(((e,r)=>{i.toBlob((t=>e(t)),t)}))},no=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===n.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let r=0;r=n)break;e[o]=e[o+1]=e[o+2]=(128&r)/128*255,e[o+3]=255,r<<=1}}}else if(Number(t.format)===n.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let r=0;r{let e;await new Promise(((i,r)=>{e=new Image,e.onload=()=>i(e),e.onerror=r,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),r=i.getContext("2d");return i.width=e.width,i.height=e.height,r.drawImage(e,0,0),{bytes:Uint8Array.from(r.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class oo{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const r=no(t);return to(r,e,i)}async drawOnImage(t,e,i,r=4294901760,n=1,s){let o;if(t instanceof Blob)o=await so(t);else if("string"==typeof t){let e=await w(t,"blob");o=await so(e)}return await new Promise(((t,a)=>{let h=$();tt[h]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},J.postMessage({type:"utility_drawOnImage",id:h,body:{dsImage:o,drawingItem:e instanceof Array?e:[e],color:r,thickness:n,type:i}})}))}}const ao="undefined"==typeof self,ho=(()=>{if(!ao&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),lo=t=>{if(null==t&&(t="./"),ao);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};null==at.utility&&(at.utility=ho),lt.utility={js:!0,wasm:!0};const co="1.2.10";"string"!=typeof at.std&&C(at.std.version,co)<0&&(at.std={version:co,path:lo(ho+`../../dynamsoft-capture-vision-std@${co}/dist/`)});const uo="2.2.30";(!at.dip||"string"!=typeof at.dip&&C(at.dip.version,uo)<0)&&(at.dip={version:uo,path:lo(ho+`../../dynamsoft-image-processing@${uo}/dist/`)});class fo{static getVersion(){return`1.2.20(Worker: ${st.utility&&st.utility.worker||"Not Loaded"}, Wasm: ${st.utility&&st.utility.wasm||"Not Loaded"})`}}const go={barcode:2,text_line:4,detected_quad:8,normalized_image:16},mo=t=>Object.values(go).includes(t)||go.hasOwnProperty(t),po=(t,e)=>"string"==typeof t?e[go[t]]:e[t],_o=(t,e,i)=>{"string"==typeof t?e[go[t]]=i:e[t]=i};class vo{constructor(){this.verificationEnabled={[dt.CRIT_BARCODE]:!1,[dt.CRIT_TEXT_LINE]:!0,[dt.CRIT_DETECTED_QUAD]:!0,[dt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateFilterEnabled={[dt.CRIT_BARCODE]:!1,[dt.CRIT_TEXT_LINE]:!1,[dt.CRIT_DETECTED_QUAD]:!1,[dt.CRIT_NORMALIZED_IMAGE]:!1},this.duplicateForgetTime={[dt.CRIT_BARCODE]:3e3,[dt.CRIT_TEXT_LINE]:3e3,[dt.CRIT_DETECTED_QUAD]:3e3,[dt.CRIT_NORMALIZED_IMAGE]:3e3}}enableResultCrossVerification(t,e){mo(t)&&_o(t,this.verificationEnabled,e)}isResultCrossVerificationEnabled(t){return!!mo(t)&&po(t,this.verificationEnabled)}enableResultDeduplication(t,e){mo(t)&&_o(t,this.duplicateFilterEnabled,e)}isResultDeduplicationEnabled(t){return!!mo(t)&&po(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){mo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),_o(t,this.duplicateForgetTime,e))}getDuplicateForgetTime(t){return mo(t)?po(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[dt.CRIT_BARCODE,dt.CRIT_TEXT_LINE,dt.CRIT_DETECTED_QUAD];for(let i=0;i{if(!T&&document.currentScript){let _=document.currentScript.src,B=_.indexOf("?");if(-1!=B)_=_.substring(0,B);else{let B=_.indexOf("#");-1!=B&&(_=_.substring(0,B))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"})(),R=_=>{if(null==_&&(_="./"),T);else{let B=document.createElement("a");B.href=_,_=B.href}return _.endsWith("/")||(_+="/"),_};null==_.dbr&&(_.dbr=D),B.dbr={js:!1,wasm:!0,deps:["license","dip"]},A.dbr={};const F="1.2.0";"string"!=typeof _.std&&I(_.std.version,F)<0&&(_.std={version:F,path:R(D+`../../dynamsoft-capture-vision-std@${F}/dist/`)});const O="2.2.10";(!_.dip||"string"!=typeof _.dip&&I(_.dip.version,O)<0)&&(_.dip={version:O,path:R(D+`../../dynamsoft-image-processing@${O}/dist/`)});class C{static getVersion(){const _=E.dbr&&E.dbr.wasm,B=E.dbr&&E.dbr.worker;return`10.2.10(Worker: ${B||"Not Loaded"}, Wasm: ${_||"Not Loaded"})`}}const S="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};var t,N,n,i;!function(_){_[_.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",_[_.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",_[_.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(t||(t={})),function(_){_[_.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",_[_.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",_[_.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",_[_.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(N||(N={})),function(_){_[_.LM_AUTO=1]="LM_AUTO",_[_.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",_[_.LM_STATISTICS=4]="LM_STATISTICS",_[_.LM_LINES=8]="LM_LINES",_[_.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",_[_.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",_[_.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",_[_.LM_CENTRE=128]="LM_CENTRE",_[_.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",_[_.LM_REV=-2147483648]="LM_REV",_[_.LM_SKIP=0]="LM_SKIP"}(n||(n={})),function(_){_[_.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",_[_.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",_[_.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",_[_.DM_SMOOTHING=8]="DM_SMOOTHING",_[_.DM_MORPHING=16]="DM_MORPHING",_[_.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",_[_.DM_SHARPENING=64]="DM_SHARPENING",_[_.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",_[_.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",_[_.DM_REV=-2147483648]="DM_REV",_[_.DM_SKIP=0]="DM_SKIP"}(i||(i={}));export{C as BarcodeReaderModule,S as EnumBarcodeFormat,i as EnumDeblurMode,t as EnumExtendedBarcodeResultType,n as EnumLocalizationMode,N as EnumQRCodeErrorCorrectionLevel}; diff --git a/dist/dbr.js b/dist/dbr.js deleted file mode 100644 index 48349de7..00000000 --- a/dist/dbr.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! -* Dynamsoft JavaScript Library -* @product Dynamsoft Barcode Reader JS Edition -* @website http://www.dynamsoft.com -* @copyright Copyright 2024, Dynamsoft Corporation -* @author Dynamsoft -* @version 10.2.10 -* @fileoverview Dynamsoft JavaScript Library for Barcode Reader -* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ -*/ -!function(_,B){"object"==typeof exports&&"undefined"!=typeof module?B(exports,require("dynamsoft-core")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core"],B):B(((_="undefined"!=typeof globalThis?globalThis:_||self).Dynamsoft=_.Dynamsoft||{},_.Dynamsoft.DBR={}),_.Dynamsoft.Core)}(this,(function(_,B){"use strict";const A="undefined"==typeof self,E=(()=>{if(!A&&document.currentScript){let _=document.currentScript.src,B=_.indexOf("?");if(-1!=B)_=_.substring(0,B);else{let B=_.indexOf("#");-1!=B&&(_=_.substring(0,B))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"})(),e=_=>{if(null==_&&(_="./"),A);else{let B=document.createElement("a");B.href=_,_=B.href}return _.endsWith("/")||(_+="/"),_};null==B.engineResourcePaths.dbr&&(B.engineResourcePaths.dbr=E),B.workerAutoResources.dbr={js:!1,wasm:!0,deps:["license","dip"]},B.mapPackageRegister.dbr={};const I="1.2.0";"string"!=typeof B.engineResourcePaths.std&&B.compareVersion(B.engineResourcePaths.std.version,I)<0&&(B.engineResourcePaths.std={version:I,path:e(E+`../../dynamsoft-capture-vision-std@${I}/dist/`)});const n="2.2.10";(!B.engineResourcePaths.dip||"string"!=typeof B.engineResourcePaths.dip&&B.compareVersion(B.engineResourcePaths.dip.version,n)<0)&&(B.engineResourcePaths.dip={version:n,path:e(E+`../../dynamsoft-image-processing@${n}/dist/`)});const R="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};var D,T,t,F;_.EnumExtendedBarcodeResultType=void 0,(D=_.EnumExtendedBarcodeResultType||(_.EnumExtendedBarcodeResultType={}))[D.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",D[D.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",D[D.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",_.EnumQRCodeErrorCorrectionLevel=void 0,(T=_.EnumQRCodeErrorCorrectionLevel||(_.EnumQRCodeErrorCorrectionLevel={}))[T.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",T[T.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",T[T.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",T[T.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",_.EnumLocalizationMode=void 0,(t=_.EnumLocalizationMode||(_.EnumLocalizationMode={}))[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",_.EnumDeblurMode=void 0,(F=_.EnumDeblurMode||(_.EnumDeblurMode={}))[F.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",F[F.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",F[F.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",F[F.DM_SMOOTHING=8]="DM_SMOOTHING",F[F.DM_MORPHING=16]="DM_MORPHING",F[F.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",F[F.DM_SHARPENING=64]="DM_SHARPENING",F[F.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",F[F.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",F[F.DM_REV=-2147483648]="DM_REV",F[F.DM_SKIP=0]="DM_SKIP",_.BarcodeReaderModule=class{static getVersion(){const _=B.innerVersions.dbr&&B.innerVersions.dbr.wasm,A=B.innerVersions.dbr&&B.innerVersions.dbr.worker;return`10.2.10(Worker: ${A||"Not Loaded"}, Wasm: ${_||"Not Loaded"})`}},_.EnumBarcodeFormat=R,Object.defineProperty(_,"__esModule",{value:!0})})); diff --git a/dist/dbr.mjs b/dist/dbr.mjs deleted file mode 100644 index 07e7469f..00000000 --- a/dist/dbr.mjs +++ /dev/null @@ -1,11 +0,0 @@ -/*! -* Dynamsoft JavaScript Library -* @product Dynamsoft Barcode Reader JS Edition -* @website http://www.dynamsoft.com -* @copyright Copyright 2024, Dynamsoft Corporation -* @author Dynamsoft -* @version 10.2.10 -* @fileoverview Dynamsoft JavaScript Library for Barcode Reader -* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ -*/ -import{engineResourcePaths as _,workerAutoResources as B,mapPackageRegister as A,compareVersion as I,innerVersions as E}from"dynamsoft-core";const T="undefined"==typeof self,D=(()=>{if(!T&&document.currentScript){let _=document.currentScript.src,B=_.indexOf("?");if(-1!=B)_=_.substring(0,B);else{let B=_.indexOf("#");-1!=B&&(_=_.substring(0,B))}return _.substring(0,_.lastIndexOf("/")+1)}return"./"})(),R=_=>{if(null==_&&(_="./"),T);else{let B=document.createElement("a");B.href=_,_=B.href}return _.endsWith("/")||(_+="/"),_};null==_.dbr&&(_.dbr=D),B.dbr={js:!1,wasm:!0,deps:["license","dip"]},A.dbr={};const F="1.2.0";"string"!=typeof _.std&&I(_.std.version,F)<0&&(_.std={version:F,path:R(D+`../../dynamsoft-capture-vision-std@${F}/dist/`)});const O="2.2.10";(!_.dip||"string"!=typeof _.dip&&I(_.dip.version,O)<0)&&(_.dip={version:O,path:R(D+`../../dynamsoft-image-processing@${O}/dist/`)});class C{static getVersion(){const _=E.dbr&&E.dbr.wasm,B=E.dbr&&E.dbr.worker;return`10.2.10(Worker: ${B||"Not Loaded"}, Wasm: ${_||"Not Loaded"})`}}const S="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};var t,N,n,i;!function(_){_[_.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",_[_.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",_[_.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(t||(t={})),function(_){_[_.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",_[_.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",_[_.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",_[_.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(N||(N={})),function(_){_[_.LM_AUTO=1]="LM_AUTO",_[_.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",_[_.LM_STATISTICS=4]="LM_STATISTICS",_[_.LM_LINES=8]="LM_LINES",_[_.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",_[_.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",_[_.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",_[_.LM_CENTRE=128]="LM_CENTRE",_[_.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",_[_.LM_REV=-2147483648]="LM_REV",_[_.LM_SKIP=0]="LM_SKIP"}(n||(n={})),function(_){_[_.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",_[_.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",_[_.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",_[_.DM_SMOOTHING=8]="DM_SMOOTHING",_[_.DM_MORPHING=16]="DM_MORPHING",_[_.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",_[_.DM_SHARPENING=64]="DM_SHARPENING",_[_.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",_[_.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",_[_.DM_REV=-2147483648]="DM_REV",_[_.DM_SKIP=0]="DM_SKIP"}(i||(i={}));export{C as BarcodeReaderModule,S as EnumBarcodeFormat,i as EnumDeblurMode,t as EnumExtendedBarcodeResultType,n as EnumLocalizationMode,N as EnumQRCodeErrorCorrectionLevel}; diff --git a/dist/dbr.no-content-bundle.esm.js b/dist/dbr.no-content-bundle.esm.js new file mode 100644 index 00000000..0e595564 --- /dev/null +++ b/dist/dbr.no-content-bundle.esm.js @@ -0,0 +1,11 @@ +/*! +* Dynamsoft JavaScript Library +* @product Dynamsoft Barcode Reader JS Edition Bundle +* @website http://www.dynamsoft.com +* @copyright Copyright 2024, Dynamsoft Corporation +* @author Dynamsoft +* @version 10.2.1000 +* @fileoverview Dynamsoft JavaScript Library for Barcode Reader +* More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ +*/ +import{CoreModule as e}from"dynamsoft-core";export*from"dynamsoft-core";export*from"dynamsoft-license";export*from"dynamsoft-capture-vision-router";export*from"dynamsoft-camera-enhancer";export*from"dynamsoft-barcode-reader";export*from"dynamsoft-utility";let t="./";if(document.currentScript){let e=document.currentScript.src,r=e.indexOf("?");if(-1!=r)e=e.substring(0,r);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}t=e.substring(0,e.lastIndexOf("/")+1)}const r=e=>{null==e&&(e="./");let t=document.createElement("a");return t.href=e,(e=t.href).endsWith("/")||(e+="/"),e};e.engineResourcePaths={std:r(t+"../../dynamsoft-capture-vision-std@1.2.10/dist/"),dip:r(t+"../../dynamsoft-image-processing@2.2.30/dist/"),core:r(t+"../../dynamsoft-core@3.2.30/dist/"),license:r(t+"../../dynamsoft-license@3.2.21/dist/"),cvr:r(t+"../../dynamsoft-capture-vision-router@2.2.30/dist/"),dce:r(t+"../../dynamsoft-camera-enhancer@4.0.3/dist/"),dbr:r(t+"../../dynamsoft-barcode-reader@10.2.10/dist/")}; diff --git a/dist/dbr.wasm b/dist/dbr.wasm deleted file mode 100644 index ec157ef9..00000000 Binary files a/dist/dbr.wasm and /dev/null differ diff --git a/dist/types/class/BarcodeReaderModule.d.ts b/dist/types/class/BarcodeReaderModule.d.ts deleted file mode 100644 index b25548d1..00000000 --- a/dist/types/class/BarcodeReaderModule.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default class BarcodeReaderModule { - static getVersion(): string; -} diff --git a/dist/types/dbr.d.ts b/dist/types/dbr.d.ts deleted file mode 100644 index 355af656..00000000 --- a/dist/types/dbr.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import BarcodeReaderModule from "./class/BarcodeReaderModule"; -import { EnumBarcodeFormat } from "./enum/EnumBarcodeFormat"; -import { EnumExtendedBarcodeResultType } from "./enum/EnumExtendedBarcodeResultType"; -import { EnumQRCodeErrorCorrectionLevel } from "./enum/EnumQRCodeErrorCorrectionLevel"; -import { EnumLocalizationMode } from "./enum/EnumLocalizationMode"; -import { EnumDeblurMode } from "./enum/EnumDeblurMode"; -import { AztecDetails } from "./interface/AztecDetails"; -import { BarcodeDetails } from "./interface/BarcodeDetails"; -import { BarcodeResultItem } from "./interface/BarcodeResultItem"; -import { DataMatrixDetails } from "./interface/DataMatrixDetails"; -import { DecodedBarcodesResult } from "./interface/DecodedBarcodesResult"; -import { ExtendedBarcodeResult } from "./interface/ExtendedBarcodeResult"; -import { OneDCodeDetails } from "./interface/OneDCodeDetails"; -import { PDF417Details } from "./interface/PDF417Details"; -import { QRCodeDetails } from "./interface/QRCodeDetails"; -import { SimplifiedBarcodeReaderSettings } from "./interface/SimplifiedBarcodeReaderSettings"; -import { CandidateBarcodeZonesUnit } from "./interface/CandidateBarcodeZonesUnit"; -import { ComplementedBarcodeImageUnit } from "./interface/ComplementedBarcodeImageUnit"; -import { DecodedBarcodeElement } from "./interface/DecodedBarcodeElement"; -import { DecodedBarcodesUnit } from "./interface/DecodedBarcodesUnit"; -import { DeformationResistedBarcodeImageUnit } from "./interface/DeformationResistedBarcodeImageUnit"; -import { LocalizedBarcodeElement } from "./interface/LocalizedBarcodeElement"; -import { LocalizedBarcodesUnit } from "./interface/LocalizedBarcodesUnit"; -import { ScaledUpBarcodeImageUnit } from "./interface/ScaledUpBarcodeImageUnit"; -import { CandidateBarcodeZone } from "./interface/CandidateBarcodeZone"; -import { DeformationResistedBarcode } from "./interface/DeformationResistedBarcode"; -export { BarcodeReaderModule, EnumBarcodeFormat, EnumExtendedBarcodeResultType, EnumQRCodeErrorCorrectionLevel, EnumLocalizationMode, EnumDeblurMode, AztecDetails, BarcodeDetails, BarcodeResultItem, DataMatrixDetails, DecodedBarcodesResult, ExtendedBarcodeResult, OneDCodeDetails, PDF417Details, QRCodeDetails, SimplifiedBarcodeReaderSettings, CandidateBarcodeZone, CandidateBarcodeZonesUnit, ComplementedBarcodeImageUnit, DecodedBarcodeElement, DecodedBarcodesUnit, DeformationResistedBarcodeImageUnit, LocalizedBarcodeElement, LocalizedBarcodesUnit, ScaledUpBarcodeImageUnit, DeformationResistedBarcode }; diff --git a/dist/types/enum/EnumExtendedBarcodeResultType.d.ts b/dist/types/enum/EnumExtendedBarcodeResultType.d.ts deleted file mode 100644 index 98dd367e..00000000 --- a/dist/types/enum/EnumExtendedBarcodeResultType.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export declare enum EnumExtendedBarcodeResultType { - EBRT_STANDARD_RESULT = 0, - EBRT_CANDIDATE_RESULT = 1, - EBRT_PARTIAL_RESULT = 2 -} diff --git a/dist/types/enum/enumbarcodeformat.d.ts b/dist/types/enum/enumbarcodeformat.d.ts deleted file mode 100644 index a120f5d7..00000000 --- a/dist/types/enum/enumbarcodeformat.d.ts +++ /dev/null @@ -1,197 +0,0 @@ -declare const EnumBarcodeFormat: { - /**No barcode format in BarcodeFormat*/ - BF_NULL: bigint; - /**All supported formats in BarcodeFormat*/ - BF_ALL: bigint; - /**Use the default barcode format settings*/ - BF_DEFAULT: bigint; - /**Combined value of BF_CODABAR, BF_CODE_128, BF_CODE_39, BF_CODE_39_Extended, BF_CODE_93, BF_EAN_13, BF_EAN_8, INDUSTRIAL_25, BF_ITF, BF_UPC_A, BF_UPC_E, BF_MSI_CODE; */ - BF_ONED: bigint; - /**Combined value of BF_GS1_DATABAR_OMNIDIRECTIONAL, BF_GS1_DATABAR_TRUNCATED, BF_GS1_DATABAR_STACKED, BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL, BF_GS1_DATABAR_EXPANDED, BF_GS1_DATABAR_EXPANDED_STACKED, BF_GS1_DATABAR_LIMITED*/ - BF_GS1_DATABAR: bigint; - /**Code 39 */ - BF_CODE_39: bigint; - /**Code 128 */ - BF_CODE_128: bigint; - /**Code 93 */ - BF_CODE_93: bigint; - /**Codabar */ - BF_CODABAR: bigint; - /**Interleaved 2 of 5 */ - BF_ITF: bigint; - /**EAN-13 */ - BF_EAN_13: bigint; - /**EAN-8 */ - BF_EAN_8: bigint; - /**UPC-A */ - BF_UPC_A: bigint; - /**UPC-E */ - BF_UPC_E: bigint; - /**Industrial 2 of 5 */ - BF_INDUSTRIAL_25: bigint; - /**CODE39 Extended */ - BF_CODE_39_EXTENDED: bigint; - /**GS1 Databar Omnidirectional*/ - BF_GS1_DATABAR_OMNIDIRECTIONAL: bigint; - /**GS1 Databar Truncated*/ - BF_GS1_DATABAR_TRUNCATED: bigint; - /**GS1 Databar Stacked*/ - BF_GS1_DATABAR_STACKED: bigint; - /**GS1 Databar Stacked Omnidirectional*/ - BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL: bigint; - /**GS1 Databar Expanded*/ - BF_GS1_DATABAR_EXPANDED: bigint; - /**GS1 Databar Expaned Stacked*/ - BF_GS1_DATABAR_EXPANDED_STACKED: bigint; - /**GS1 Databar Limited*/ - BF_GS1_DATABAR_LIMITED: bigint; - /**Patch code. */ - BF_PATCHCODE: bigint; - /**PDF417 */ - BF_CODE_32: bigint; - /**PDF417 */ - BF_PDF417: bigint; - /**QRCode */ - BF_QR_CODE: bigint; - /**DataMatrix */ - BF_DATAMATRIX: bigint; - /**AZTEC */ - BF_AZTEC: bigint; - /**MAXICODE */ - BF_MAXICODE: bigint; - /**Micro QR Code*/ - BF_MICRO_QR: bigint; - /**Micro PDF417*/ - BF_MICRO_PDF417: bigint; - /**GS1 Composite Code*/ - BF_GS1_COMPOSITE: bigint; - /**MSI Code*/ - BF_MSI_CODE: bigint; - BF_CODE_11: bigint; - BF_TWO_DIGIT_ADD_ON: bigint; - BF_FIVE_DIGIT_ADD_ON: bigint; - BF_MATRIX_25: bigint; - /**Combined value of BF2_USPSINTELLIGENTMAIL, BF2_POSTNET, BF2_PLANET, BF2_AUSTRALIANPOST, BF2_RM4SCC.*/ - BF_POSTALCODE: bigint; - /**Nonstandard barcode */ - BF_NONSTANDARD_BARCODE: bigint; - /**USPS Intelligent Mail.*/ - BF_USPSINTELLIGENTMAIL: bigint; - /**Postnet.*/ - BF_POSTNET: bigint; - /**Planet.*/ - BF_PLANET: bigint; - /**Australian Post.*/ - BF_AUSTRALIANPOST: bigint; - /**Royal Mail 4-State Customer Barcode.*/ - BF_RM4SCC: bigint; - /**KIX.*/ - BF_KIX: bigint; - /**DotCode.*/ - BF_DOTCODE: bigint; - /**_PHARMACODE_ONE_TRACK.*/ - BF_PHARMACODE_ONE_TRACK: bigint; - /**PHARMACODE_TWO_TRACK.*/ - BF_PHARMACODE_TWO_TRACK: bigint; - /**PHARMACODE.*/ - BF_PHARMACODE: bigint; -} | { - /**No barcode format in BarcodeFormat*/ - BF_NULL: string; - /**All supported formats in BarcodeFormat*/ - BF_ALL: string; - /**Use the default barcode format settings*/ - BF_DEFAULT: string; - /**Combined value of BF_CODABAR, BF_CODE_128, BF_CODE_39, BF_CODE_39_Extended, BF_CODE_93, BF_EAN_13, BF_EAN_8, INDUSTRIAL_25, BF_ITF, BF_UPC_A, BF_UPC_E, BF_MSI_CODE; */ - BF_ONED: string; - /**Combined value of BF_GS1_DATABAR_OMNIDIRECTIONAL, BF_GS1_DATABAR_TRUNCATED, BF_GS1_DATABAR_STACKED, BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL, BF_GS1_DATABAR_EXPANDED, BF_GS1_DATABAR_EXPANDED_STACKED, BF_GS1_DATABAR_LIMITED*/ - BF_GS1_DATABAR: string; - /**Code 39 */ - BF_CODE_39: string; - /**Code 128 */ - BF_CODE_128: string; - /**Code 93 */ - BF_CODE_93: string; - /**Codabar */ - BF_CODABAR: string; - /**Interleaved 2 of 5 */ - BF_ITF: string; - /**EAN-13 */ - BF_EAN_13: string; - /**EAN-8 */ - BF_EAN_8: string; - /**UPC-A */ - BF_UPC_A: string; - /**UPC-E */ - BF_UPC_E: string; - /**Industrial 2 of 5 */ - BF_INDUSTRIAL_25: string; - /**CODE39 Extended */ - BF_CODE_39_EXTENDED: string; - /**GS1 Databar Omnidirectional*/ - BF_GS1_DATABAR_OMNIDIRECTIONAL: string; - /**GS1 Databar Truncated*/ - BF_GS1_DATABAR_TRUNCATED: string; - /**GS1 Databar Stacked*/ - BF_GS1_DATABAR_STACKED: string; - /**GS1 Databar Stacked Omnidirectional*/ - BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL: string; - /**GS1 Databar Expanded*/ - BF_GS1_DATABAR_EXPANDED: string; - /**GS1 Databar Expaned Stacked*/ - BF_GS1_DATABAR_EXPANDED_STACKED: string; - /**GS1 Databar Limited*/ - BF_GS1_DATABAR_LIMITED: string; - /**Patch code. */ - BF_PATCHCODE: string; - /**PDF417 */ - BF_CODE_32: string; - /**PDF417 */ - BF_PDF417: string; - /**QRCode */ - BF_QR_CODE: string; - /**DataMatrix */ - BF_DATAMATRIX: string; - /**AZTEC */ - BF_AZTEC: string; - /**MAXICODE */ - BF_MAXICODE: string; - /**Micro QR Code*/ - BF_MICRO_QR: string; - /**Micro PDF417*/ - BF_MICRO_PDF417: string; - /**GS1 Composite Code*/ - BF_GS1_COMPOSITE: string; - /**MSI Code*/ - BF_MSI_CODE: string; - BF_CODE_11: string; - BF_TWO_DIGIT_ADD_ON: string; - BF_FIVE_DIGIT_ADD_ON: string; - BF_MATRIX_25: string; - /**Combined value of BF2_USPSINTELLIGENTMAIL, BF2_POSTNET, BF2_PLANET, BF2_AUSTRALIANPOST, BF2_RM4SCC.*/ - BF_POSTALCODE: string; - /**Nonstandard barcode */ - BF_NONSTANDARD_BARCODE: string; - /**USPS Intelligent Mail.*/ - BF_USPSINTELLIGENTMAIL: string; - /**Postnet.*/ - BF_POSTNET: string; - /**Planet.*/ - BF_PLANET: string; - /**Australian Post.*/ - BF_AUSTRALIANPOST: string; - /**Royal Mail 4-State Customer Barcode.*/ - BF_RM4SCC: string; - /**KIX.*/ - BF_KIX: string; - /**DotCode.*/ - BF_DOTCODE: string; - /**_PHARMACODE_ONE_TRACK.*/ - BF_PHARMACODE_ONE_TRACK: string; - /**PHARMACODE_TWO_TRACK.*/ - BF_PHARMACODE_TWO_TRACK: string; - /**PHARMACODE.*/ - BF_PHARMACODE: string; -}; -type EnumBarcodeFormat = BigInt; -export { EnumBarcodeFormat }; diff --git a/dist/types/enum/enumdeblurmode.d.ts b/dist/types/enum/enumdeblurmode.d.ts deleted file mode 100644 index 615305d3..00000000 --- a/dist/types/enum/enumdeblurmode.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** Label: DBRJS10.0.10-Check - * @enum EnumDeblurMode - * - * Describes the deblur mode. - */ -export declare enum EnumDeblurMode { - /**Performs deblur process using the direct binarization algorithm.*/ - DM_DIRECT_BINARIZATION = 1, - /**Performs deblur process using the threshold binarization algorithm.*/ - DM_THRESHOLD_BINARIZATION = 2, - /**Performs deblur process using the gray equalization algorithm.*/ - DM_GRAY_EQUALIZATION = 4, - /**Performs deblur process using the smoothing algorithm.*/ - DM_SMOOTHING = 8, - /**Performs deblur process using the morphing algorithm.*/ - DM_MORPHING = 16, - /**Performs deblur process using the deep analysis algorithm.*/ - DM_DEEP_ANALYSIS = 32, - /**Performs deblur process using the sharpening algorithm.*/ - DM_SHARPENING = 64, - /**Performs deblur process based on the binary image from the localization process.*/ - DM_BASED_ON_LOC_BIN = 128, - /**Performs deblur process using the sharpening and smoothing algorithm.*/ - DM_SHARPENING_SMOOTHING = 256, - /**Reserved setting for deblur mode.*/ - DM_REV = -2147483648, - /**Skips the deblur process.*/ - DM_SKIP = 0 -} diff --git a/dist/types/enum/enumlocalizationmode.d.ts b/dist/types/enum/enumlocalizationmode.d.ts deleted file mode 100644 index 2ab27e85..00000000 --- a/dist/types/enum/enumlocalizationmode.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** Label: DBRJS10.0.10-Check - * @enum EnumLocalizationMode - * - * Describes the localization mode. - */ -export declare enum EnumLocalizationMode { - /**Not supported yet. */ - LM_AUTO = 1, - /**Localizes barcodes by searching for connected blocks. This algorithm usually gives best result and it is recommended to set ConnectedBlocks to the highest priority. */ - LM_CONNECTED_BLOCKS = 2, - /**Localizes barcodes by groups of contiguous black-white regions. This is optimized for QRCode and DataMatrix. */ - LM_STATISTICS = 4, - /**Localizes barcodes by searching for groups of lines. This is optimized for 1D and PDF417 barcodes. */ - LM_LINES = 8, - /**Localizes barcodes quickly. This mode is recommended in interactive scenario. Check @ref LM for available argument settings.*/ - LM_SCAN_DIRECTLY = 16, - /**Localizes barcodes by groups of marks.This is optimized for DPM codes. */ - LM_STATISTICS_MARKS = 32, - /**Localizes barcodes by groups of connected blocks and lines.This is optimized for postal codes. */ - LM_STATISTICS_POSTAL_CODE = 64, - /**Localizes barcodes from the centre of the image. Check @ref LM for available argument settings. */ - LM_CENTRE = 128, - /**Localizes 1D barcodes fast. Check @ref LM for available argument settings. */ - LM_ONED_FAST_SCAN = 256, - LM_REV = -2147483648, - /**Skips localization. */ - LM_SKIP = 0 -} diff --git a/dist/types/enum/enumqrcodeerrorcorrectionlevel.d.ts b/dist/types/enum/enumqrcodeerrorcorrectionlevel.d.ts deleted file mode 100644 index 7f10dd46..00000000 --- a/dist/types/enum/enumqrcodeerrorcorrectionlevel.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export declare enum EnumQRCodeErrorCorrectionLevel { - QRECL_ERROR_CORRECTION_H = 0, - QRECL_ERROR_CORRECTION_L = 1, - QRECL_ERROR_CORRECTION_M = 2, - QRECL_ERROR_CORRECTION_Q = 3 -} diff --git a/dist/types/interface/AztecDetails.d.ts b/dist/types/interface/AztecDetails.d.ts deleted file mode 100644 index e02f7d85..00000000 --- a/dist/types/interface/AztecDetails.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { BarcodeDetails } from "./BarcodeDetails"; -export interface AztecDetails extends BarcodeDetails { - rows: number; - columns: number; - layerNumber: number; -} diff --git a/dist/types/interface/BarcodeDetails.d.ts b/dist/types/interface/BarcodeDetails.d.ts deleted file mode 100644 index fe694dc7..00000000 --- a/dist/types/interface/BarcodeDetails.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export interface BarcodeDetails { -} diff --git a/dist/types/interface/BarcodeResultItem.d.ts b/dist/types/interface/BarcodeResultItem.d.ts deleted file mode 100644 index 235f0a35..00000000 --- a/dist/types/interface/BarcodeResultItem.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { CapturedResultItem, Quadrilateral } from "dynamsoft-core"; -import { BarcodeDetails } from "./BarcodeDetails"; -import { EnumBarcodeFormat } from "../enum/EnumBarcodeFormat"; -export interface BarcodeResultItem extends CapturedResultItem { - format: EnumBarcodeFormat; - formatString: string; - text: string; - bytes: Array; - location: Quadrilateral; - confidence: number; - angle: number; - moduleSize: number; - details: BarcodeDetails; - isMirrored: boolean; - isDPM: boolean; -} diff --git a/dist/types/interface/CandidateBarcodeZone.d.ts b/dist/types/interface/CandidateBarcodeZone.d.ts deleted file mode 100644 index 120c7bc1..00000000 --- a/dist/types/interface/CandidateBarcodeZone.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Quadrilateral } from "dynamsoft-core"; -import { EnumBarcodeFormat } from "../enum/EnumBarcodeFormat"; -/** - * The `CandidateBarcodeZone` interface represents a candidate barcode zone. - */ -export interface CandidateBarcodeZone { - /** Location of the candidate barcode zone within the image. */ - location: Quadrilateral; - /** Possible formats of the localized barcode. */ - possibleFormats: EnumBarcodeFormat; -} diff --git a/dist/types/interface/CandidateBarcodeZonesUnit.d.ts b/dist/types/interface/CandidateBarcodeZonesUnit.d.ts deleted file mode 100644 index 32c0371e..00000000 --- a/dist/types/interface/CandidateBarcodeZonesUnit.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { IntermediateResultExtraInfo, IntermediateResultUnit } from "dynamsoft-core"; -import { CandidateBarcodeZone } from "./CandidateBarcodeZone"; -/** - * The `CandidateBarcodeZonesUnit` interface extends the `IntermediateResultUnit` interface and represents a unit of candidate barcode zones. - */ -export interface CandidateBarcodeZonesUnit extends IntermediateResultUnit { - /** Array of candidate barcode zones represented as quadrilaterals. */ - candidateBarcodeZones: Array; -} -declare module "dynamsoft-capture-vision-router" { - interface IntermediateResultReceiver { - onCandidateBarcodeZonesUnitReceived?: (result: CandidateBarcodeZonesUnit, info: IntermediateResultExtraInfo) => void; - } -} diff --git a/dist/types/interface/ComplementedBarcodeImageUnit.d.ts b/dist/types/interface/ComplementedBarcodeImageUnit.d.ts deleted file mode 100644 index 6498524b..00000000 --- a/dist/types/interface/ComplementedBarcodeImageUnit.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { DSImageData, IntermediateResultExtraInfo, IntermediateResultUnit, Quadrilateral } from "dynamsoft-core"; -export interface ComplementedBarcodeImageUnit extends IntermediateResultUnit { - imageData: DSImageData; - location: Quadrilateral; -} -declare module "dynamsoft-capture-vision-router" { - interface IntermediateResultReceiver { - onComplementedBarcodeImageUnitReceived?: (result: ComplementedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; - } -} diff --git a/dist/types/interface/DataMatrixDetails.d.ts b/dist/types/interface/DataMatrixDetails.d.ts deleted file mode 100644 index e618b17d..00000000 --- a/dist/types/interface/DataMatrixDetails.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { BarcodeDetails } from "./BarcodeDetails"; -export interface DataMatrixDetails extends BarcodeDetails { - rows: number; - columns: number; - dataRegionRows: number; - dataRegionColumns: number; - dataRegionNumber: number; -} diff --git a/dist/types/interface/DecodedBarcodeElement.d.ts b/dist/types/interface/DecodedBarcodeElement.d.ts deleted file mode 100644 index 9e0d62b6..00000000 --- a/dist/types/interface/DecodedBarcodeElement.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { RegionObjectElement } from "dynamsoft-core"; -import { BarcodeDetails } from "./BarcodeDetails"; -import { ExtendedBarcodeResult } from "./ExtendedBarcodeResult"; -import { EnumBarcodeFormat } from "../enum/EnumBarcodeFormat"; -export interface DecodedBarcodeElement extends RegionObjectElement { - format: EnumBarcodeFormat; - formatString: string; - text: string; - bytes: Array; - details: BarcodeDetails; - isDPM: boolean; - isMirrored: boolean; - angle: number; - moduleSize: number; - confidence: number; - extendedBarcodeResults: Array; -} diff --git a/dist/types/interface/DecodedBarcodesResult.d.ts b/dist/types/interface/DecodedBarcodesResult.d.ts deleted file mode 100644 index d2ef80e6..00000000 --- a/dist/types/interface/DecodedBarcodesResult.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ImageTag } from "dynamsoft-core"; -import { BarcodeResultItem } from "./BarcodeResultItem"; -export interface DecodedBarcodesResult { - readonly originalImageHashId: string; - readonly originalImageTag: ImageTag; - readonly barcodeResultItems: Array; - readonly errorCode: number; - readonly errorString: string; -} -declare module "dynamsoft-capture-vision-router" { - interface CapturedResultReceiver { - onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; - } - interface CapturedResultFilter { - onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; - } -} diff --git a/dist/types/interface/DecodedBarcodesUnit.d.ts b/dist/types/interface/DecodedBarcodesUnit.d.ts deleted file mode 100644 index 45b7bbf4..00000000 --- a/dist/types/interface/DecodedBarcodesUnit.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { IntermediateResultExtraInfo, IntermediateResultUnit } from "dynamsoft-core"; -import { DecodedBarcodeElement } from "./DecodedBarcodeElement"; -export interface DecodedBarcodesUnit extends IntermediateResultUnit { - decodedBarcodes: Array; -} -declare module "dynamsoft-capture-vision-router" { - interface IntermediateResultReceiver { - onDecodedBarcodesReceived?: (result: DecodedBarcodesUnit, info: IntermediateResultExtraInfo) => void; - } -} diff --git a/dist/types/interface/DeformationResistedBarcode.d.ts b/dist/types/interface/DeformationResistedBarcode.d.ts deleted file mode 100644 index 7228fb0c..00000000 --- a/dist/types/interface/DeformationResistedBarcode.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { DSImageData, Quadrilateral } from "dynamsoft-core"; -import { EnumBarcodeFormat } from "../enum/EnumBarcodeFormat"; -/** - * The `DeformationResistedBarcode` interface represents a deformation-resisted barcode image. - */ -export interface DeformationResistedBarcode { - /** Format of the barcode, as defined by `EnumBarcodeFormat`. */ - format: EnumBarcodeFormat; - /** Image data of the deformation-resisted barcode image. */ - imageData: DSImageData; - /** Location of the deformation-resisted barcode within the image. */ - location: Quadrilateral; -} diff --git a/dist/types/interface/DeformationResistedBarcodeImageUnit.d.ts b/dist/types/interface/DeformationResistedBarcodeImageUnit.d.ts deleted file mode 100644 index 1a470a2e..00000000 --- a/dist/types/interface/DeformationResistedBarcodeImageUnit.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { IntermediateResultExtraInfo, IntermediateResultUnit } from "dynamsoft-core"; -import { DeformationResistedBarcode } from "./DeformationResistedBarcode"; -/** - * The `DeformationResistedBarcodeImageUnit` interface extends the `IntermediateResultUnit` interface and represents a unit that holds the deformation-resisted barcode which includes the corresponding image data, its location, and the barcode format. - */ -export interface DeformationResistedBarcodeImageUnit extends IntermediateResultUnit { - /** The deformation-resisted barcode. */ - deformationResistedBarcode: DeformationResistedBarcode; -} -declare module "dynamsoft-capture-vision-router" { - interface IntermediateResultReceiver { - onDeformationResistedBarcodeImageUnitReceived?: (result: DeformationResistedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; - } -} diff --git a/dist/types/interface/ExtendedBarcodeResult.d.ts b/dist/types/interface/ExtendedBarcodeResult.d.ts deleted file mode 100644 index e83763d1..00000000 --- a/dist/types/interface/ExtendedBarcodeResult.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { DSImageData } from "dynamsoft-core"; -import { EnumExtendedBarcodeResultType } from "../enum/EnumExtendedBarcodeResultType"; -import { DecodedBarcodeElement } from "./DecodedBarcodeElement"; -export interface ExtendedBarcodeResult extends DecodedBarcodeElement { - extendedBarcodeResultType: EnumExtendedBarcodeResultType; - deformation: number; - clarity: number; - samplingImage: DSImageData; -} diff --git a/dist/types/interface/LocalizedBarcodeElement.d.ts b/dist/types/interface/LocalizedBarcodeElement.d.ts deleted file mode 100644 index 1d87cecf..00000000 --- a/dist/types/interface/LocalizedBarcodeElement.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RegionObjectElement } from "dynamsoft-core"; -import { EnumBarcodeFormat } from "../enum/EnumBarcodeFormat"; -export interface LocalizedBarcodeElement extends RegionObjectElement { - possibleFormats: EnumBarcodeFormat; - possibleFormatsString: string; - angle: number; - moduleSize: number; - confidence: number; -} diff --git a/dist/types/interface/LocalizedBarcodesUnit.d.ts b/dist/types/interface/LocalizedBarcodesUnit.d.ts deleted file mode 100644 index dd13c9cc..00000000 --- a/dist/types/interface/LocalizedBarcodesUnit.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { IntermediateResultExtraInfo, IntermediateResultUnit } from "dynamsoft-core"; -import { LocalizedBarcodeElement } from "./LocalizedBarcodeElement"; -export interface LocalizedBarcodesUnit extends IntermediateResultUnit { - localizedBarcodes: Array; -} -declare module "dynamsoft-capture-vision-router" { - interface IntermediateResultReceiver { - onLocalizedBarcodesReceived?: (result: LocalizedBarcodesUnit, info: IntermediateResultExtraInfo) => void; - } -} diff --git a/dist/types/interface/OneDCodeDetails.d.ts b/dist/types/interface/OneDCodeDetails.d.ts deleted file mode 100644 index d75b1dbd..00000000 --- a/dist/types/interface/OneDCodeDetails.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { BarcodeDetails } from "./BarcodeDetails"; -export interface OneDCodeDetails extends BarcodeDetails { - startCharsBytes: Array; - stopCharsBytes: Array; - checkDigitBytes: Array; - startPatternRange: number; - middlePatternRange: number; - endPatternRange: number; -} diff --git a/dist/types/interface/PDF417Details.d.ts b/dist/types/interface/PDF417Details.d.ts deleted file mode 100644 index 88c78430..00000000 --- a/dist/types/interface/PDF417Details.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { BarcodeDetails } from "./BarcodeDetails"; -export interface PDF417Details extends BarcodeDetails { - rows: number; - columns: number; - errorCorrectionLevel: number; - hasLeftRowIndicator: boolean; - hasRightRowIndicator: boolean; -} diff --git a/dist/types/interface/QRCodeDetails.d.ts b/dist/types/interface/QRCodeDetails.d.ts deleted file mode 100644 index f11f6b0a..00000000 --- a/dist/types/interface/QRCodeDetails.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { BarcodeDetails } from "./BarcodeDetails"; -export interface QRCodeDetails extends BarcodeDetails { - rows: number; - columns: number; - errorCorrectionLevel: number; - version: number; - model: number; - mode: number; - page: number; - totalPage: number; - parityData: number; -} diff --git a/dist/types/interface/ScaledUpBarcodeImageUnit.d.ts b/dist/types/interface/ScaledUpBarcodeImageUnit.d.ts deleted file mode 100644 index d1dd5867..00000000 --- a/dist/types/interface/ScaledUpBarcodeImageUnit.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { DSImageData, IntermediateResultExtraInfo, IntermediateResultUnit } from "dynamsoft-core"; -export interface ScaledUpBarcodeImageUnit extends IntermediateResultUnit { - imageData: DSImageData; -} -declare module "dynamsoft-capture-vision-router" { - interface IntermediateResultReceiver { - onScaledUpBarcodeImageUnitReceived?: (result: ScaledUpBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; - } -} diff --git a/dist/types/interface/SimplifiedBarcodeReaderSettings.d.ts b/dist/types/interface/SimplifiedBarcodeReaderSettings.d.ts deleted file mode 100644 index 4407d9a0..00000000 --- a/dist/types/interface/SimplifiedBarcodeReaderSettings.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { EnumGrayscaleEnhancementMode, EnumGrayscaleTransformationMode } from "dynamsoft-core"; -import { EnumBarcodeFormat } from "../enum/EnumBarcodeFormat"; -export interface SimplifiedBarcodeReaderSettings { - barcodeFormatIds: EnumBarcodeFormat; - expectedBarcodesCount: number; - grayscaleTransformationModes: Array; - grayscaleEnhancementModes: Array; - localizationModes: Array; - deblurModes: Array; - minResultConfidence: number; - minBarcodeTextLength: number; - barcodeTextRegExPattern: string; -} diff --git a/package.json b/package.json index d86f835b..b2eb20d9 100644 --- a/package.json +++ b/package.json @@ -1,49 +1,39 @@ { - "name": "dynamsoft-barcode-reader", - "version": "10.2.10", + "name": "dynamsoft-barcode-reader-bundle", + "version": "10.2.1000", "description": "Dynamsoft Barcode Reader JS is a recognition SDK which enables you to embed barcode reading functionality in your web, desktop, and mobile applications. With a few lines of JavaScript code, you can develop a robust application to scan a linear barcode, QR Code, DaraMatrix, PDF417, and Aztec Code.", - "files": [ - "/dist/*.js", - "/dist/*.mjs", - "/dist/*.html", - "/dist/*.wasm", - "/dist/**/*.d.ts", - "/dist/**/*.json", - "LEGAL.txt", - "API Reference.url", - "samples.url" - ], - "homepage": "https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/index.html", - "main": "./dist/dbr.js", - "module": "./dist/dbr.esm.js", + "main": "dist/dbr.bundle.js", + "module": "dist/dbr.no-content-bundle.esm.js", "exports": { - ".": { - "types": { - "require": "./dist/types/dbr.d.cts", - "import": "./dist/types/dbr.d.ts" - }, - "import": "./dist/dbr.esm.js", - "require": "./dist/dbr.js" + "import": { + "types": "./dist/dbr.bundle.esm.d.ts", + "default": "./dist/dbr.no-content-bundle.esm.js" + }, + "require": { + "types": "./dist/dbr.bundle.d.ts", + "default": "./dist/dbr.bundle.js" } }, - "types": "./dist/types/dbr.d.ts", "sideEffects": true, + "types": "dist/dbr.bundle.esm.d.ts", + "type": "module", + "files": [ + "/dist", + "LEGAL.txt", + "LICENSE" + ], "scripts": { "build": "rollup -c --environment BUILD:production", - "update:readme": "updateReadme --package=dynamsoft-barcode-reader --version=latest --html", - "update:prod": "updatePackage --package=dynamsoft-barcode-reader --version=auto --env=production --tag=latest", - "update:beta": "updatePackage --package=dynamsoft-barcode-reader --version=auto --env=beta --tag=beta", - "update:iv": "updatePackage --package=dynamsoft-barcode-reader --version=auto --env=internalVersion --tag=iv", - "update:dev": "updatePackage --package=dynamsoft-barcode-reader --version=auto --env=development --tag=latest", + "test": "echo \"Error: no test specified\" && exit 1", + "update:readme": "updateReadme --package=dynamsoft-barcode-reader-bundle --version=latest --branch=preview --html", "updateLink:npm": "updateLink --source=npm", "updateLink:zip": "updateLink --source=zip", "updateLink:github": "updateLink --source=github", - "makeZip": "makeZip --package=dynamsoft-barcode-reader --version=auto --sampleBranch=_dev --structure=new --otherPkgs=dynamsoft-capture-vision-std dynamsoft-image-processing dynamsoft-core dynamsoft-license dynamsoft-capture-vision-router dynamsoft-utility dynamsoft-camera-enhancer", - "makeZip_dev": "makeZip --package=dynamsoft-barcode-reader --version=auto --sampleBranch=_dev --structure=new --otherPkgs=@dynamsoft/dynamsoft-capture-vision-std @dynamsoft/dynamsoft-image-processing @dynamsoft/dynamsoft-core @dynamsoft/dynamsoft-license @dynamsoft/dynamsoft-capture-vision-router @dynamsoft/dynamsoft-utility @dynamsoft/dynamsoft-camera-enhancer", - "easyPublish": "npm run update:dev && npm i dynamsoft-core@npm:@dynamsoft/dynamsoft-core@latest && npm run build && npm publish", - "ep-no-core": "npm run update:dev && npm run build && npm publish", - "overridesCore:prod": "npm pkg delete overrides && npm pkg set dependencies.dynamsoft-core=\"^3.2.10\" && npm pkg set devDependencies.dynamsoft-camera-enhancer=\"^4.0.2\" && npm pkg set devDependencies.dynamsoft-capture-vision-router=\"^2.2.10\" && npm pkg set devDependencies.dynamsoft-license=\"^3.2.10\" && npm pkg set devDependencies.dynamsoft-utility=\"^1.2.10\"", - "overridesCore:dev": "npm pkg set overrides.dynamsoft-core=$dynamsoft-core && npm pkg set overrides.dynamsoft-camera-enhancer=$dynamsoft-camera-enhancer && npm pkg set overrides.dynamsoft-capture-vision-router=$dynamsoft-capture-vision-router && npm pkg set overrides.dynamsoft-license=$dynamsoft-license && npm pkg set overrides.dynamsoft-utility=$dynamsoft-utility && npm pkg set dependencies.dynamsoft-core=npm:@dynamsoft/dynamsoft-core@latest && npm pkg set devDependencies.dynamsoft-camera-enhancer=npm:@dynamsoft/dynamsoft-camera-enhancer@latest && npm pkg set devDependencies.dynamsoft-capture-vision-router=npm:@dynamsoft/dynamsoft-capture-vision-router@latest && npm pkg set devDependencies.dynamsoft-license=npm:@dynamsoft/dynamsoft-license@latest && npm pkg set devDependencies.dynamsoft-utility=npm:@dynamsoft/dynamsoft-utility@latest && npm update dynamsoft-core --no-package-lock && npm update dynamsoft-camera-enhancer --no-package-lock && npm update dynamsoft-capture-vision-router --no-package-lock && npm update dynamsoft-license --no-package-lock && npm update dynamsoft-utility --no-package-lock" + "update:prod": "updatePackage --package=dynamsoft-barcode-reader-bundle --version=auto --env=production --tag=latest", + "update:beta": "updatePackage --package=dynamsoft-barcode-reader-bundle --version=auto --env=beta --tag=beta", + "update:iv": "updatePackage --package=dynamsoft-barcode-reader-bundle --version=auto --env=internalVersion --tag=iv", + "update:dev": "updatePackage --package=dynamsoft-barcode-reader-bundle --version=auto --env=development --tag=latest", + "makeZip": "makeZip --package=dynamsoft-barcode-reader-bundle --version=auto --sampleBranch=_dev --structure=new --otherPkgs=dynamsoft-capture-vision-std dynamsoft-image-processing dynamsoft-core dynamsoft-license dynamsoft-capture-vision-router dynamsoft-utility dynamsoft-camera-enhancer dynamsoft-barcode-reader" }, "keywords": [ "HTML5 barcode", @@ -60,40 +50,36 @@ ], "author": { "name": "Dynamsoft", - "url": "https://www.dynamsoft.com" - }, - "publishConfig": { - "registry": "https://registry.npmjs.org/", - "tag": "latest" + "url": "https://www.dynamsoft.com", + "email": "support@dynamsoft.com" }, "license": "SEE LICENSE IN LICENSE", "repository": { "type": "git", "url": "https://github.com/dynamsoft/barcode-reader-javascript.git" }, - "maintainers": [ - { - "name": "Dynamsoft", - "email": "support@dynamsoft.com" - } - ], + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "tag": "latest" + }, "devDependencies": { - "@dynamsoft/rd2-scripts": "^0.1.17", - "@rollup/plugin-node-resolve": "^15.0.1", - "@rollup/plugin-replace": "^5.0.2", - "@rollup/plugin-terser": "^0.4.3", - "@rollup/plugin-typescript": "^11.0.0", + "@dynamsoft/rd2-scripts": "^0.1.18", + "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^5.0.5", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", "@scannerproxy/curscript-path": "^2.0.1", - "@types/node": "^20.7.1", - "dynamsoft-camera-enhancer": "^4.0.2", - "dynamsoft-capture-vision-router": "^2.2.10", - "dynamsoft-license": "^3.2.10", - "dynamsoft-utility": "^1.2.10", - "rollup": "^2.79.1", + "rollup": "^3.29.3", + "rollup-plugin-dts": "^6.1.0", "tslib": "^2.6.2", "typescript": "^4.9.5" }, "dependencies": { - "dynamsoft-core": "^3.2.10" + "dynamsoft-barcode-reader": "10.2.10", + "dynamsoft-camera-enhancer": "4.0.3", + "dynamsoft-capture-vision-router": "2.2.30", + "dynamsoft-core": "3.2.30", + "dynamsoft-license": "3.2.21", + "dynamsoft-utility": "1.2.20" } } diff --git a/samples.url b/samples.url index 00e29b17..0b037453 100644 --- a/samples.url +++ b/samples.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.2.10 \ No newline at end of file +URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.2.1000 \ No newline at end of file