diff --git a/README.html b/README.html index 4b6cc55..c7af32b 100644 --- a/README.html +++ b/README.html @@ -220,6 +220,16 @@

Build a Web-Based Barcode Scanner Using Just a Few Lines of JavaScript

+ +

This user guide provides a step-by-step walkthrough of a "Hello World" web application using the BarcodeScanner JavaScript Edition.

The BarcodeScanner class offers the following features:

diff --git a/README.md b/README.md index d60d057..9d88fd5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,14 @@ # Build a Web-Based Barcode Scanner Using Just a Few Lines of JavaScript + +- [Build a Web-Based Barcode Scanner Using Just a Few Lines of JavaScript](#build-a-web-based-barcode-scanner-using-just-a-few-lines-of-javascript) + - [License](#license) + - [Quick Start: Hello World Example](#quick-start-hello-world-example) + - [Step 1: Setting up the HTML and Including the Barcode Scanner](#step-1-setting-up-the-html-and-including-the-barcode-scanner) + - [Step 2: Initializing the Barcode Scanner](#step-2-initializing-the-barcode-scanner) + - [Step 3: Launching the Barcode Scanner](#step-3-launching-the-barcode-scanner) + - [Next Steps](#next-steps) + This user guide provides a step-by-step walkthrough of a "Hello World" web application using the `BarcodeScanner` JavaScript Edition. The `BarcodeScanner` class offers the following features: @@ -35,18 +44,11 @@ new Dynamsoft.BarcodeScanner().launch().then(result=>alert(result.barcodeResults ## License - - When getting started with Barcode Scanner, we recommend [getting your own 30-day trial license](https://www.dynamsoft.com/customer/license/trialLicense/?product=dbr&utm_source=github&package=js) - - -> [!IMPORTANT] -> The trial license can be renewed via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense/?product=dbr&utm_source=github&package=js) twice, each time for another 15 days, giving you a total of 60 days to develop your own application using the solution. Please contact the [Dynamsoft Support Team](https://www.dynamsoft.com/company/contact/) if you need more time for a full evaluation. + ## Quick Start: Hello World Example @@ -54,7 +56,7 @@ If you are fully satisfied with the solution and would like to move forward with - + + ``` -In this example, we include the precompiled Barcode Scanner SDK script via public CDN in the header. +In this example, we include the precompiled Barcode Scanner SDK script via public CDN in the body.
@@ -115,24 +117,24 @@ The simplest way to include the SDK is to use either the [**jsDelivr**](https:// - jsDelivr ```html - + ``` - UNPKG ```html - + ``` When using a framework such as **React**, **Vue** or **Angular**, we recommend adding the package as a dependency using a package manager such as **npm** or **yarn**: ```sh - npm i dynamsoft-barcode-reader-bundle@11.0.6000 + npm i dynamsoft-barcode-reader-bundle@11.2.2000 # or - yarn add dynamsoft-barcode-reader-bundle@11.0.6000 + yarn add dynamsoft-barcode-reader-bundle@11.2.2000 ``` -As for package managers like **npm** or **yarn**, you likely need to specify the location of the engine files as a link to a CDN. Please see the [BarcodeScannerConfig API](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) for a code snippet on how to set the `engineResourcePaths`. +When using package managers like **npm** or **yarn**, you likely need to specify the location of the engine files as a link to a CDN. Please see the [BarcodeScannerConfig API](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) for a code snippet on how to set the `engineResourcePaths`.
@@ -142,14 +144,14 @@ Alternatively, you may choose to download the SDK and host the files on your own - From the website - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=11.0.60&utm_source=github&product=dbr&package=js) + [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=11.2.20&utm_source=github&product=dbr&package=js) The resources are located in the `./dist/` directory. - From npm ```sh - npm i dynamsoft-barcode-reader-bundle@11.0.6000 + npm i dynamsoft-barcode-reader-bundle@11.2.2000 ``` The resources are located at the path `node_modules/`, without `@`. You can copy it elsewhere and add `@` tag. @@ -157,10 +159,10 @@ Alternatively, you may choose to download the SDK and host the files on your own > [!IMPORTANT] > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. -You can typically include SDK like this: +You can typically include the SDK like this: ```html - + ```
@@ -172,9 +174,9 @@ Barcode Scanner comes with a **Ready-to-Use UI**. When the Barcode Scanner launc ```js // Initialize the Dynamsoft Barcode Scanner -const barcodescanner = new Dynamsoft.BarcodeScanner({ +const barcodeScanner = new Dynamsoft.BarcodeScanner({ // Please don't forget to replace YOUR_LICENSE_KEY_HERE - license: "YOUR_LICENSE_KEY_HERE", + license: "YOUR_LICENSE_KEY_HERE", }); ``` @@ -185,7 +187,7 @@ This is the **simplest** way to initialize the Barcode Scanner. The configuratio ```js // Initialize the Dynamsoft Barcode Scanner in MULTI_UNIQUE mode -const barcodescanner = new Dynamsoft.BarcodeScanner({ +const barcodeScanner = new Dynamsoft.BarcodeScanner({ license: "YOUR_LICENSE_KEY_HERE", scanMode: Dynamsoft.EnumScanMode.SM_MULTI_UNIQUE, }); @@ -196,7 +198,7 @@ const barcodescanner = new Dynamsoft.BarcodeScanner({ ```js (async () => { // Launch the scanner and wait for the result - const result = await barcodescanner.launch(); + const result = await barcodeScanner.launch(); // Display the first detected barcode's text in an alert if (result.barcodeResults.length) { alert(result.barcodeResults[0].text); @@ -207,12 +209,14 @@ const barcodescanner = new Dynamsoft.BarcodeScanner({ Now that the Barcode Scanner has been initialized and configured, it is ready to be launched! Upon launch, the Barcode Scanner presents the main **`BarcodeScannerView`** UI in its container on the page, and is ready to start scanning. By default, we use the `SINGLE` scanning mode, which means only one decoding result will be included in the final result. In the code above, we directly alerted the successfully decoded barcode text on the page. > [!NOTE] -> In the Hello World sample, after a successfully decoding process, the scanner closes and the user is met with an empty page. In order to open the scanner again, the user must refresh the page. You may choose to implement a more user-friendly behavior in a production environment, such as presenting the user with an option to re-open the Barcode Scanner upon closing it. +> In the Hello World sample, after a successful decoding process, the scanner closes and the user is met with an empty page. In order to open the scanner again, the user must refresh the page. You may choose to implement a more user-friendly behavior in a production environment, such as presenting the user with an option to re-open the Barcode Scanner upon closing it. +> [!TIP] +> When running performance benchmarks, make sure to disable the console, avoid using `console.log()`, and run in non-debug mode whenever possible. This ensures that your benchmark results reflect true performance without interference from logging or debugging overhead. ## Next Steps -Now that you've implemented the basic functionality, here are some recommended next steps to further explore the capabilities of the Barcode Scanner +Now that you've implemented the basic functionality, here are some recommended next steps to further explore the capabilities of the Barcode Scanner: 1. Learn how to [Customize the Barcode Scanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/barcode-scanner-customization.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=11.0.6000) -3. Learn about the [APIs of BarcodeScanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html?ver=11.0.6000) +2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=11.2.2000) +3. Learn about the [APIs of BarcodeScanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html?ver=11.2.2000) diff --git a/dist/dbr.bundle.d.ts b/dist/dbr.bundle.d.ts index d028953..7cc85c5 100644 --- a/dist/dbr.bundle.d.ts +++ b/dist/dbr.bundle.d.ts @@ -532,9 +532,8 @@ interface PostMessageBody { engineResourcePaths?: EngineResourcePaths; autoResources?: WorkerAutoResources; names?: string[]; + wasmLoadOptions: WasmLoadOptions; _bundleEnv?: "DCV" | "DBR"; - _useSimd?: boolean; - _useMLBackend?: boolean; } type PathInfo = { version: string; @@ -586,6 +585,11 @@ interface WasmVersions { interface MapController { [key: string]: ((body: any, taskID: number, instanceID?: number) => void); } +type WasmType = "baseline" | "ml" | "ml-simd" | "ml-simd-pthread" | "auto"; +interface WasmLoadOptions { + wasmType?: WasmType; + pthreadPoolSize?: number; +} type MimeType = "image/png" | "image/jpeg"; declare const mapAsyncDependency: { @@ -621,9 +625,11 @@ declare class CoreModule { static get _bDebug(): boolean; static set _bDebug(value: boolean); static _bundleEnv: "DCV" | "DBR"; - static _useMLBackend: boolean; static get _workerName(): string; - static _useSimd: boolean; + private static _wasmLoadOptions; + static get wasmLoadOptions(): WasmLoadOptions; + static set wasmLoadOptions(options: WasmLoadOptions); + static loadedWasmType: Exclude; /** * Initiates the loading process for the .wasm file(s) corresponding to the specified module(s). * If a module relies on other modules, the other modules will be loaded as well. @@ -632,6 +638,17 @@ declare class CoreModule { */ static isModuleLoaded(name?: string): boolean; static loadWasm(): Promise; + /** + * An event that fires during the loading of a WebAssembly module (.wasm). + * + * @param filePath The path of the wasm file. + * @param tag Indicates the ongoing status of the file download ("starting", "in progress", "completed"). + * @param progress An object indicating the progress of the download, with `loaded` and `total` bytes. + */ + static onWasmLoadProgressChanged: (filePath: string, tag: "starting" | "in progress" | "completed", progress: { + loaded: number; + total: number; + }) => void; /** * Detect environment and get a report. */ @@ -683,7 +700,13 @@ interface CapturedResultItem { interface OriginalImageResultItem extends CapturedResultItem { /** The image data associated with this result item. */ - readonly imageData: DSImageData; + imageData: DSImageData; + /** Converts the image data into an HTMLCanvasElement for display or further manipulation in web applications. */ + toCanvas: () => HTMLCanvasElement; + /** Converts the image data into an HTMLImageElement of a specified MIME type ('image/png' or 'image/jpeg'). */ + toImage: (MIMEType: "image/png" | "image/jpeg") => HTMLImageElement; + /** Converts the image data into a Blob object of a specified MIME type ('image/png' or 'image/jpeg'). */ + toBlob: (MIMEType: "image/png" | "image/jpeg") => Promise; } interface Point { @@ -1198,7 +1221,11 @@ declare const isQuad: (value: any) => value is Quadrilateral; */ declare const isRect: (value: any) => value is Rect; -declare const requestResource: (url: string, type: "text" | "blob" | "arraybuffer") => Promise; +declare const requestResource: (url: string, type: "text" | "blob" | "arraybuffer", callbacks?: { + loadstartCallback?: () => any; + progressCallback?: (pe: any) => any; + loadendCallback?: () => any; +}) => Promise; declare const checkIsLink: (str: string) => boolean; declare const compareVersion: (strV1: string, strV2: string) => number; declare const handleEngineResourcePaths: (engineResourcePaths: EngineResourcePaths) => EngineResourcePaths; @@ -1228,7 +1255,7 @@ declare const productNameMap: { readonly dcvBundle: "dynamsoft-capture-vision-bundle"; }; -export { Arc, BinaryImageUnit, CapturedResultBase, CapturedResultItem, ColourImageUnit, Contour, ContoursUnit, CoreModule, Corner, DSFile, DSImageData, DSRect, DwtInfo, Edge, EngineResourcePaths, EnhancedGrayscaleImageUnit, EnumBufferOverflowProtectionMode, EnumCapturedResultItemType, EnumColourChannelUsageType, EnumCornerType, EnumCrossVerificationStatus, EnumErrorCode, EnumGrayscaleEnhancementMode, EnumGrayscaleTransformationMode, EnumImageCaptureDistanceMode, EnumImageFileFormat, EnumImagePixelFormat, EnumImageTagType, EnumIntermediateResultUnitType, EnumModuleName, EnumPDFReadingMode, EnumRasterDataSource, EnumRegionObjectElementType, EnumSectionType, EnumTransformMatrixType, ErrorInfo, FileImageTag, GrayscaleImageUnit, ImageSourceAdapter, ImageSourceErrorListener, ImageTag, InnerVersions, IntermediateResult, IntermediateResultExtraInfo, IntermediateResultUnit, LineSegment, LineSegmentsUnit, MapController, MimeType, ObservationParameters, OriginalImageResultItem, PDFReadingParameter, PathInfo, Point, Polygon, PostMessageBody, PredetectedRegionElement, PredetectedRegionsUnit, Quadrilateral, Rect, RegionObjectElement, ScaledColourImageUnit, ShortLinesUnit, TextRemovedBinaryImageUnit, TextZone, TextZonesUnit, TextureDetectionResultUnit, TextureRemovedBinaryImageUnit, TextureRemovedGrayscaleImageUnit, TransformedGrayscaleImageUnit, Warning, WasmVersions, WorkerAutoResources, _getNorImageData, _saveToFile, _toBlob, _toCanvas, _toImage, bDebug, checkIsLink, compareVersion, doOrWaitAsyncDependency, getNextTaskID, handleEngineResourcePaths, innerVersions, isArc, isContour, isDSImageData, isDSRect, isImageTag, isLineSegment, isObject, isOriginalDsImageData, isPoint, isPolygon, isQuad, isRect, isSimdSupported, mapAsyncDependency, mapPackageRegister, mapTaskCallBack, onLog, productNameMap, requestResource, setBDebug, setOnLog, waitAsyncDependency, worker, workerAutoResources }; +export { Arc, BinaryImageUnit, CapturedResultBase, CapturedResultItem, ColourImageUnit, Contour, ContoursUnit, CoreModule, Corner, DSFile, DSImageData, DSRect, DwtInfo, Edge, EngineResourcePaths, EnhancedGrayscaleImageUnit, EnumBufferOverflowProtectionMode, EnumCapturedResultItemType, EnumColourChannelUsageType, EnumCornerType, EnumCrossVerificationStatus, EnumErrorCode, EnumGrayscaleEnhancementMode, EnumGrayscaleTransformationMode, EnumImageCaptureDistanceMode, EnumImageFileFormat, EnumImagePixelFormat, EnumImageTagType, EnumIntermediateResultUnitType, EnumModuleName, EnumPDFReadingMode, EnumRasterDataSource, EnumRegionObjectElementType, EnumSectionType, EnumTransformMatrixType, ErrorInfo, FileImageTag, GrayscaleImageUnit, ImageSourceAdapter, ImageSourceErrorListener, ImageTag, InnerVersions, IntermediateResult, IntermediateResultExtraInfo, IntermediateResultUnit, LineSegment, LineSegmentsUnit, MapController, MimeType, ObservationParameters, OriginalImageResultItem, PDFReadingParameter, PathInfo, Point, Polygon, PostMessageBody, PredetectedRegionElement, PredetectedRegionsUnit, Quadrilateral, Rect, RegionObjectElement, ScaledColourImageUnit, ShortLinesUnit, TextRemovedBinaryImageUnit, TextZone, TextZonesUnit, TextureDetectionResultUnit, TextureRemovedBinaryImageUnit, TextureRemovedGrayscaleImageUnit, TransformedGrayscaleImageUnit, Warning, WasmLoadOptions, WasmType, WasmVersions, WorkerAutoResources, _getNorImageData, _saveToFile, _toBlob, _toCanvas, _toImage, bDebug, checkIsLink, compareVersion, doOrWaitAsyncDependency, getNextTaskID, handleEngineResourcePaths, innerVersions, isArc, isContour, isDSImageData, isDSRect, isImageTag, isLineSegment, isObject, isOriginalDsImageData, isPoint, isPolygon, isQuad, isRect, isSimdSupported, mapAsyncDependency, mapPackageRegister, mapTaskCallBack, onLog, productNameMap, requestResource, setBDebug, setOnLog, waitAsyncDependency, worker, workerAutoResources }; @@ -1241,9 +1268,9 @@ interface CapturedResult extends CapturedResultBase { /** The decoded barcode results within the original image. */ decodedBarcodesResult?: DecodedBarcodesResult; /** The recognized textLine results within the original image. */ - // recognizedTextLinesResult?: RecognizedTextLinesResult; + recognizedTextLinesResult?: RecognizedTextLinesResult; /** The processed document results within the original image. */ - // processedDocumentResult?: ProcessedDocumentResult; + processedDocumentResult?: ProcessedDocumentResult; /** The parsed results within the original image. */ parsedResult?: ParsedResult; } @@ -1261,7 +1288,10 @@ declare class CapturedResultReceiver { * @param result The original image result, an instance of `OriginalImageResultItem`. */ onOriginalImageResultReceived?: (result: OriginalImageResultItem) => void; - [key: string]: any; + onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; + onRecognizedTextLinesReceived?: (result: RecognizedTextLinesResult) => void; + onProcessedDocumentResultReceived?: (result: ProcessedDocumentResult) => void; + onParsedResultsReceived?: (result: ParsedResult) => void; } declare class BufferedItemsManager { @@ -1281,7 +1311,7 @@ declare class BufferedItemsManager { * Gets the buffered character items. * @return the buffered character items */ - getBufferedCharacterItemSet(): Promise>; + getBufferedCharacterItemSet(): Promise>; } declare class IntermediateResultReceiver { @@ -1310,6 +1340,22 @@ declare class IntermediateResultReceiver { onTextZonesUnitReceived?: (result: TextZonesUnit, info: IntermediateResultExtraInfo) => void; onTextRemovedBinaryImageUnitReceived?: (result: TextRemovedBinaryImageUnit, info: IntermediateResultExtraInfo) => void; onShortLinesUnitReceived?: (result: ShortLinesUnit, info: IntermediateResultExtraInfo) => void; + onCandidateBarcodeZonesUnitReceived?: (result: CandidateBarcodeZonesUnit, info: IntermediateResultExtraInfo) => void; + onComplementedBarcodeImageUnitReceived?: (result: ComplementedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; + onDecodedBarcodesReceived?: (result: DecodedBarcodesUnit, info: IntermediateResultExtraInfo) => void; + onDeformationResistedBarcodeImageUnitReceived?: (result: DeformationResistedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; + onLocalizedBarcodesReceived?: (result: LocalizedBarcodesUnit, info: IntermediateResultExtraInfo) => void; + onScaledBarcodeImageUnitReceived?: (result: ScaledBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; + onLocalizedTextLinesReceived?: (result: LocalizedTextLinesUnit, info: IntermediateResultExtraInfo) => void; + onRawTextLinesUnitReceived?: (result: RawTextLinesUnit, info: IntermediateResultExtraInfo) => void; + onRecognizedTextLinesReceived?: (result: RecognizedTextLinesUnit, info: IntermediateResultExtraInfo) => void; + onCandidateQuadEdgesUnitReceived?: (result: CandidateQuadEdgesUnit, info: IntermediateResultExtraInfo) => void; + onCornersUnitReceived?: (result: CornersUnit, info: IntermediateResultExtraInfo) => void; + onDeskewedImageReceived?: (result: DeskewedImageUnit, info: IntermediateResultExtraInfo) => void; + onDetectedQuadsReceived?: (result: DetectedQuadsUnit, info: IntermediateResultExtraInfo) => void; + onEnhancedImageReceived?: (result: EnhancedImageUnit, info: IntermediateResultExtraInfo) => void; + onLogicLinesUnitReceived?: (result: LogicLinesUnit, info: IntermediateResultExtraInfo) => void; + onLongLinesUnitReceived?: (result: LongLinesUnit, info: IntermediateResultExtraInfo) => void; } declare class IntermediateResultManager { @@ -1383,21 +1429,44 @@ interface SimplifiedCaptureVisionSettings { * Specifies the basic settings for the barcode reader module. It is of type `SimplifiedBarcodeReaderSettings`. */ barcodeSettings: SimplifiedBarcodeReaderSettings; + /** + * Specifies the basic settings for the document normalizer module. It is of type `SimplifiedDocumentNormalizerSettings`. + */ + documentSettings: SimplifiedDocumentNormalizerSettings; + /** + * Specifies the basic settings for the label recognizer module. It is of type `SimplifiedLabelRecognizerSettings`. + */ + labelSettings: SimplifiedLabelRecognizerSettings; } interface CapturedResultFilter { onOriginalImageResultReceived?: (result: OriginalImageResultItem) => void; - [key: string]: any; + onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; + onRecognizedTextLinesReceived?: (result: RecognizedTextLinesResult) => void; + onProcessedDocumentResultReceived?: (result: ProcessedDocumentResult) => void; + onParsedResultsReceived?: (result: ParsedResult) => void; + getFilteredResultItemTypes(): number; } declare class CaptureVisionRouter { #private; static _onLog: (message: string) => void; static _defaultTemplate: string; + private static _isNoOnnx; /** * The maximum length of the longer side of the image to be processed. The default value is 2048 pixels in mobile devices and 4096 pixels in desktop browser. */ maxImageSideLength: number; + /** + * An event that fires during the loading of a recognition data file (.data). + * @param filePath The path of the recognition data file. + * @param tag Indicates the ongoing status of the file download ("starting", "in progress", "completed"). + * @param progress An object indicating the progress of the download, with `loaded` and `total` bytes. + */ + static onDataLoadProgressChanged: (filePath: string, tag: "starting" | "in progress" | "completed", progress: { + loaded: number; + total: number; + }) => void; /** * An event that fires when an error occurs from the start of capturing process. * @param error The error object that contains the error code and error string. @@ -1432,23 +1501,17 @@ declare class CaptureVisionRouter { */ static createInstance(loadPresetTemplates?: boolean): Promise; /** - * Loads a specific data file containing recognition information. This file typically comprises a Convolutional Neural Networks (CNN) model. - * @param dataName Specifies the name of the data. - * @param dataPath [Optional] Specifies the path to find the data file. If not specified, the default path points to the package "dynamsoft-capture-vision-data" which has the same root path as the packag"dynamsoft-capture-vision-router". - * - * @returns A promise that resolves once the recognition data file is successfully loaded. It does not provide any value upon resolution. - */ - static appendModelBuffer(modelName: string, dataPath?: string): Promise; + * Appends a deep learning model to the memory buffer. + * @param dataName Specifies the name of the model. + * @param dataPath [Optional] Specifies the path to find the model file. If not specified, the default path points to the package "dynamsoft-capture-vision-data". + * + * @returns A promise that resolves once the model file is successfully loaded. It does not provide any value upon resolution. + */ + static appendDLModelBuffer(modelName: string, dataPath?: string): Promise; /** - * An event that fires during the loading of a recognition data file (.data). - * @param filePath The path of the recognition data file. - * @param tag Indicates the ongoing status of the file download ("starting", "in progress", "completed"). - * @param progress An object indicating the progress of the download, with `loaded` and `total` bytes. + * Clears all deep learning models from buffer to free up memory */ - static onDataLoadProgressChanged: (filePath: string, tag: "starting" | "in progress" | "completed", progress: { - loaded: number; - total: number; - }) => void; + static clearDLModelBuffers(): Promise; private _singleFrameModeCallback; private _singleFrameModeCallbackBind; /** @@ -1506,11 +1569,21 @@ declare class CaptureVisionRouter { */ stopCapturing(): void; containsTask(templateName: string): Promise; + /** + * Switches the currently active capturing template during the image processing workflow. This allows dynamic reconfiguration of the capture process without restarting or reinitializing the system, enabling different settings or rules to be applied on the fly. + * + * @param templateName The name of the new capturing template to apply. + * + * @return A promise with an ErrorInfo object that resolves when the operation has completed, containing the result of the operation. + * + */ + switchCapturingTemplate(templateName: string): Promise; /** * Video stream capture, recursive call, loop frame capture */ private _loopReadVideo; private _reRunCurrnetFunc; + getClarity(dsimage: DSImageData, bitcount: number, wr: number, hr: number, grayThreshold: number): Promise; /** * Processes a single image or a file containing a single image to derive important information. * @param imageOrFile Specifies the image or file to be processed. The following data types are accepted: `Blob`, `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, `DSImageData`, `string`. @@ -1588,6 +1661,11 @@ declare class CaptureVisionRouter { * @returns The `IntermediateResultManager` object. */ getIntermediateResultManager(): IntermediateResultManager; + /** + * Sets the global number of threads used internally for model execution. + * @param intraOpNumThreads Number of threads used internally for model execution. + */ + static setGlobalIntraOpNumThreads(intraOpNumThreads?: number): Promise; parseRequiredResources(templateName: string): Promise<{ models: string[]; specss: string[]; @@ -1865,6 +1943,8 @@ declare enum EnumLocalizationMode { LM_CENTRE = 128, /** Specialized for quick localization of 1D barcodes, enhancing performance in fast-scan scenarios. */ LM_ONED_FAST_SCAN = 256, + /**Localizes barcodes by utilizing a neural network model. */ + LM_NEURAL_NETWORK = 512, /** Reserved for future use in localization mode settings. */ LM_REV = -2147483648, /** Omits the localization process entirely. */ @@ -1959,15 +2039,7 @@ interface DecodedBarcodesResult extends CapturedResultBase { /** * An array of `BarcodeResultItem` objects, each representing a decoded barcode within the original image. */ - readonly barcodeResultItems: Array; -} -declare module "dynamsoft-barcode-reader-bundle" { - interface CapturedResultReceiver { - onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; - } - interface CapturedResultFilter { - onDecodedBarcodesReceived?: (result: DecodedBarcodesResult) => void; - } + barcodeResultItems: Array; } interface DecodedBarcodeElement extends RegionObjectElement { @@ -2101,30 +2173,15 @@ interface CandidateBarcodeZonesUnit extends IntermediateResultUnit { /** Array of candidate barcode zones represented as quadrilaterals. */ candidateBarcodeZones: Array; } -declare module "dynamsoft-barcode-reader-bundle" { - interface IntermediateResultReceiver { - onCandidateBarcodeZonesUnitReceived?: (result: CandidateBarcodeZonesUnit, info: IntermediateResultExtraInfo) => void; - } -} interface ComplementedBarcodeImageUnit extends IntermediateResultUnit { imageData: DSImageData; location: Quadrilateral; } -declare module "dynamsoft-barcode-reader-bundle" { - interface IntermediateResultReceiver { - onComplementedBarcodeImageUnitReceived?: (result: ComplementedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; - } -} interface DecodedBarcodesUnit extends IntermediateResultUnit { decodedBarcodes: Array; } -declare module "dynamsoft-barcode-reader-bundle" { - interface IntermediateResultReceiver { - onDecodedBarcodesReceived?: (result: DecodedBarcodesUnit, info: IntermediateResultExtraInfo) => void; - } -} /** * The `DeformationResistedBarcode` interface represents a deformation-resisted barcode image. @@ -2145,11 +2202,6 @@ interface DeformationResistedBarcodeImageUnit extends IntermediateResultUnit { /** The deformation-resisted barcode. */ deformationResistedBarcode: DeformationResistedBarcode; } -declare module "dynamsoft-barcode-reader-bundle" { - interface IntermediateResultReceiver { - onDeformationResistedBarcodeImageUnitReceived?: (result: DeformationResistedBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; - } -} interface LocalizedBarcodeElement extends RegionObjectElement { /** Possible formats of the localized barcode. */ @@ -2168,21 +2220,11 @@ interface LocalizedBarcodesUnit extends IntermediateResultUnit { /** An array of `LocalizedBarcodeElement` objects, each representing a localized barcode. */ localizedBarcodes: Array; } -declare module "dynamsoft-barcode-reader-bundle" { - interface IntermediateResultReceiver { - onLocalizedBarcodesReceived?: (result: LocalizedBarcodesUnit, info: IntermediateResultExtraInfo) => void; - } -} interface ScaledBarcodeImageUnit extends IntermediateResultUnit { /** Image data of the scaled barcode. */ imageData: DSImageData; } -declare module "dynamsoft-barcode-reader-bundle" { - interface IntermediateResultReceiver { - onScaledBarcodeImageUnitReceived?: (result: ScaledBarcodeImageUnit, info: IntermediateResultExtraInfo) => void; - } -} export { BarcodeReaderModule, EnumBarcodeFormat, EnumDeblurMode, EnumExtendedBarcodeResultType, EnumLocalizationMode, EnumQRCodeErrorCorrectionLevel }; export type { AztecDetails, BarcodeDetails, BarcodeResultItem, CandidateBarcodeZone, CandidateBarcodeZonesUnit, ComplementedBarcodeImageUnit, DataMatrixDetails, DecodedBarcodeElement, DecodedBarcodesResult, DecodedBarcodesUnit, DeformationResistedBarcode, DeformationResistedBarcodeImageUnit, ExtendedBarcodeResult, LocalizedBarcodeElement, LocalizedBarcodesUnit, OneDCodeDetails, PDF417Details, QRCodeDetails, ScaledBarcodeImageUnit, SimplifiedBarcodeReaderSettings }; @@ -3313,6 +3355,7 @@ declare class CameraManager { version: number; OS: string; }; + private static _tryToReopenTime; static onWarning: (message: string) => void; /** * Check if storage is available. @@ -4161,6 +4204,17 @@ declare class CameraEnhancer extends ImageSourceAdapter { * @returns A `Point` object representing the converted x and y coordinates relative to the viewport. */ convertToScanRegionCoordinates(point: Point): Point; + /** + * Converts coordinates from the video's coordinate system under `fit: cover` mode + * back to coordinates under `fit: contain` mode. + * This is useful when you need to map points detected in a cropped/resized video (cover) + * back to the original video dimensions (contain). + * + * @param point A `Point` object representing the x and y coordinates within the video's `cover` coordinate system. + * + * @returns A `Point` object representing the converted x and y coordinates under `contain` mode. + */ + convertToContainCoordinates(point: Point): Point; /** * Releases all resources used by the `CameraEnhancer` instance. */ @@ -4717,6 +4771,16 @@ declare class CodeParserModule { * @returns A promise that resolves when the specification is loaded. It does not provide any value upon resolution. */ static loadSpec(specificationName: string | Array, specificationPath?: string): Promise; + /** + * An event that repeatedly fires during the loading of specification files. + * @param filePath Returns the path of the specification file. + * @param tag Indicates the ongoing status of the file download. Available values are "starting", "in progress", "completed". + * @param progress Shows the numerical progress of the download. + */ + static onSpecLoadProgressChanged: (filePath: string, tag: "starting" | "in progress" | "completed", progress: { + loaded: number; + total: number; + }) => void; } declare enum EnumMappingStatus { @@ -4755,14 +4819,361 @@ interface ParsedResult extends CapturedResultBase { */ parsedResultItems: Array; } -declare module "dynamsoft-capture-vision-bundle" { - interface CapturedResultReceiver { - onParsedResultsReceived?: (result: ParsedResult) => void; - } -} export { CodeParser, CodeParserModule, EnumMappingStatus, EnumValidationStatus, ParsedResult, ParsedResultItem }; + +declare class DocumentNormalizerModule { + /** + * Returns the version of the DocumentNormalizer module. + */ + static getVersion(): string; +} + +/** + * `EnumImageColourMode` determines the output colour mode of the normalized image. + */ +declare enum EnumImageColourMode { + /** Output image in color mode. */ + ICM_COLOUR = 0, + /** Output image in grayscale mode. */ + ICM_GRAYSCALE = 1, + /** Output image in binary mode. */ + ICM_BINARY = 2 +} + +interface DetectedQuadResultItem extends CapturedResultItem { + /** The location of the detected quadrilateral within the original image, represented as a quadrilateral shape. */ + location: Quadrilateral; + /** A confidence score related to the detected quadrilateral's accuracy as a document boundary. */ + confidenceAsDocumentBoundary: number; + /** Indicates whether the DetectedQuadResultItem has passed corss verification. */ + CrossVerificationStatus: EnumCrossVerificationStatus; +} + +interface DeskewedImageResultItem extends CapturedResultItem { + /** The image data for the deskewed image result. */ + imageData: DSImageData; + /** The location where the deskewed image was extracted from within the input image image of the deskew section, represented as a quadrilateral. */ + sourceLocation: Quadrilateral; + toCanvas: () => HTMLCanvasElement; + toImage: (MIMEType: "image/png" | "image/jpeg") => HTMLImageElement; + toBlob: (MIMEType: "image/png" | "image/jpeg") => Promise; +} + +interface EnhancedImageElement extends RegionObjectElement { + /** The image data for the enhanced image. */ + imageData: DSImageData; +} + +interface EnhancedImageResultItem extends CapturedResultItem { + /** The image data for the enhanced image result. */ + imageData: DSImageData; + /** Converts the enhanced image data into an HTMLCanvasElement for display or further manipulation in web applications. */ + toCanvas: () => HTMLCanvasElement; + /** Converts the enhanced image data into an HTMLImageElement of a specified MIME type ('image/png' or 'image/jpeg'). */ + toImage: (MIMEType: "image/png" | "image/jpeg") => HTMLImageElement; + /** Converts the enhanced image data into a Blob object of a specified MIME type ('image/png' or 'image/jpeg'). */ + toBlob: (MIMEType: "image/png" | "image/jpeg") => Promise; +} + +interface EnhancedImageUnit extends IntermediateResultUnit { + /** An array of `EnhancedImageElement` objects, each representing a piece of the original image after enhancement. */ + enhancedImage: EnhancedImageElement; +} + +interface CandidateQuadEdgesUnit extends IntermediateResultUnit { + /** An array of candidate edges that may form quadrilaterals, identified during image processing. */ + candidateQuadEdges: Array; +} + +interface CornersUnit extends IntermediateResultUnit { + /** An array of detected corners within the image, identified during image processing. */ + corners: Array; +} + +interface DetectedQuadElement extends RegionObjectElement { + /** A confidence score measuring the certainty that the detected quadrilateral represents the boundary of a document. */ + confidenceAsDocumentBoundary: number; +} + +interface DetectedQuadsUnit extends IntermediateResultUnit { + /** An array of `DetectedQuadElement` objects, each representing a potential document or area of interest within the image. */ + detectedQuads: Array; +} + +interface LongLinesUnit extends IntermediateResultUnit { + /** An array of long line segments detected within the image. */ + longLines: Array; +} + +interface LogicLinesUnit extends IntermediateResultUnit { + /** An array of logic line segments detected within the image. */ + logicLines: Array; +} + +interface DeskewedImageElement extends RegionObjectElement { + /** The image data for the deskewed image. */ + imageData: DSImageData; + /** A reference to another `RegionObjectElement`. */ + referencedElement: RegionObjectElement; +} + +interface DeskewedImageUnit extends IntermediateResultUnit { + /** The `DeskewedImageElement` objects representing a piece of the original image after deskewing. */ + deskewedImage: DeskewedImageElement; +} + +interface ProcessedDocumentResult extends CapturedResultBase { + /** An array of `DetectedQuadResultItem` objects, each representing a quadrilateral after document detection. */ + detectedQuadResultItems: Array; + /** An array of `DeskewedImageResultItem` objects, each representing a piece of the original image after deskewing. */ + deskewedImageResultItems: Array; + /** An array of `EnhancedImageResultItem` objects, each representing a piece of the original image after enhancement. */ + enhancedImageResultItems: Array; +} + +/** + * The `SimplifiedDocumentNormalizerSettings` interface defines simplified settings for document detection and normalization. + */ +interface SimplifiedDocumentNormalizerSettings { + /** Grayscale enhancement modes to apply for improving detection in challenging conditions. */ + grayscaleEnhancementModes: Array; + /** Grayscale transformation modes to apply, enhancing detection capability. */ + grayscaleTransformationModes: Array; + /** Color mode of the anticipated normalized page */ + colourMode: EnumImageColourMode; + /** Width and height of the anticipated normalized page. */ + pageSize: [number, number]; + /** Anticipated brightness level of the normalized image. */ + brightness: number; + /** Anticipated contrast level of the normalized image. */ + contrast: number; + /** + * Threshold for reducing the size of large images to speed up processing. + * If the size of the image's shorter edge exceeds this threshold, the image may be downscaled to decrease processing time. The standard setting is 2300. + */ + scaleDownThreshold: number; + /** The minimum ratio between the target document area and the total image area. Only those exceedingthis value will be output (measured in percentages).*/ + minQuadrilateralAreaRatio: number; + /** The number of documents expected to be detected.*/ + expectedDocumentsCount: number; +} + +export { CandidateQuadEdgesUnit, CornersUnit, DeskewedImageElement, DeskewedImageResultItem, DeskewedImageUnit, DetectedQuadElement, DetectedQuadResultItem, DetectedQuadsUnit, DocumentNormalizerModule, EnhancedImageElement, EnhancedImageResultItem, EnhancedImageUnit, EnumImageColourMode, LogicLinesUnit, LongLinesUnit, ProcessedDocumentResult, SimplifiedDocumentNormalizerSettings }; + + +declare class LabelRecognizerModule { + #private; + /** + * An event that repeatedly fires during the loading of a recognition data file (.data). + * @param filePath Returns the path of the recognition data file. + * @param tag Indicates the ongoing status of the file download. Available values are "starting", "in progress", "completed". + * @param progress Shows the numerical progress of the download. + */ + static onDataLoadProgressChanged: (filePath: string, tag: "starting" | "in progress" | "completed", progress: { + loaded: number; + total: number; + }) => void; + /** + * Returns the version of the LabelRecognizer module. + */ + static getVersion(): string; + /** + * Loads a specific data file containing confusable characters information. + * @param dataName The name of the recognition data to load. + * @param dataPath specifies the path to find the data file. If not specified, the default path points to the package “dynamsoft-capture-vision-data”. + */ + static loadConfusableCharsData(dataName: string, dataPath?: string): Promise; + /** + * Loads a specific data file containing overlapping characters information. + * @param dataName The name of the recognition data to load. + * @param dataPath specifies the path to find the data file. If not specified, the default path points to the package “dynamsoft-capture-vision-data”. + */ + static loadOverlappingCharsData(dataName: string, dataPath?: string): Promise; +} + +interface CharacterResult { + /** The highest confidence character recognized. */ + characterH: string; + /** The medium confidence character recognized. */ + characterM: string; + /** The lowest confidence character recognized. */ + characterL: string; + /** Confidence score for the highest confidence character. */ + characterHConfidence: number; + /** Confidence score for the medium confidence character. */ + characterMConfidence: number; + /** Confidence score for the lowest confidence character. */ + characterLConfidence: number; + /** The location of the recognized character within the image. */ + location: Quadrilateral; +} + +interface TextLineResultItem extends CapturedResultItem { + /** The recognized text of the line. */ + text: string; + /** The location of the text line within the image. */ + location: Quadrilateral; + /** Confidence score for the recognized text line. */ + confidence: number; + /** Results for individual characters within the text line. */ + characterResults: Array; + /** The name of the TextLineSpecification object that generated this TextLineResultItem. */ + specificationName: string; + /** The recognized raw text of the line. */ + rawText: string; +} + +declare function filterVINResult(vinItem: TextLineResultItem): string; +/** + * check if the vin code is valid + * @ignore + */ +declare function checkValidVIN(code: string): boolean; +/** + * check if the second row of passport mrz code is valid. + * check digit only exits in second row in passport mrz. + * @ignore + */ +declare function checkValidMRP(code: string): boolean; +/** + * check if the second row of visa mrz code is valid. + * check digit only exits in second row in visa mrz. + * @ignore + */ +declare function checkValidMRV(code: string): boolean; +/** + * check if the two row or third row of id card mrz code is valid. + * check digit only exits in two row or third row in id card mrz. + * @ignore + */ +declare function checkValidIDCard(code: string, codeUpperLine?: string): boolean; +declare const utilsFuncs: { + filterVINResult: typeof filterVINResult; + checkValidVIN: typeof checkValidVIN; + checkValidMRP: typeof checkValidMRP; + checkValidMRV: typeof checkValidMRV; + checkValidIDCard: typeof checkValidIDCard; +}; + +/** + * Enumerates the status of a raw text line. + */ +declare enum EnumRawTextLineStatus { + /** Localized but recognition not performed. */ + RTLS_LOCALIZED = 0, + /** Recognition failed. */ + RTLS_RECOGNITION_FAILED = 1, + /** Successfully recognized. */ + RTLS_RECOGNITION_SUCCEEDED = 2 +} + +interface LocalizedTextLineElement extends RegionObjectElement { + /** Quadrilaterals for each character in the text line. */ + characterQuads: Array; + /** The row number of the text line, starting from 1. */ + rowNumber: number; +} + +interface LocalizedTextLinesUnit extends IntermediateResultUnit { + /** An array of `LocalizedTextLineElement` objects, each representing a localized text line. */ + localizedTextLines: Array; +} + +interface RecognizedTextLineElement extends RegionObjectElement { + /** The recognized text of the line. */ + text: string; + /** Confidence score for the recognized text line. */ + confidence: number; + /** Results for individual characters within the text line. */ + characterResults: Array; + /** The row number of the text line, starting from 1. */ + rowNumber: number; + /** The name of the TextLineSpecification object that generated this RecognizedTextLineElement. */ + specificationName: string; + /** The recognized raw text of the line. */ + rawText: string; +} + +interface RecognizedTextLinesResult extends CapturedResultBase { + /** + * An array of `TextLineResultItem` objects, each representing a recognized text line within the original image. + */ + textLineResultItems: Array; +} + +interface SimplifiedLabelRecognizerSettings { + /** Name of the character model used for recognition. */ + characterModelName: string; + /** Regular expression pattern for validating recognized line strings. */ + lineStringRegExPattern: string; + /** Grayscale transformation modes to apply, enhancing detection capability. */ + grayscaleTransformationModes: Array; + /** Grayscale enhancement modes to apply for improving detection in challenging conditions. */ + grayscaleEnhancementModes: Array; + /** + * Threshold for reducing the size of large images to speed up processing. If the size of the image's shorter edge exceeds this threshold, the image may be downscaled to decrease processing time. The standard setting is 2300. */ + scaleDownThreshold: number; +} + +interface BufferedCharacterItem { + /** The buffered character value. */ + character: string; + /** The image data of the buffered character. */ + image: DSImageData; + /** An array of features, each feature object contains feature id and value of the buffered character.*/ + features: Map; +} + +interface CharacterCluster { + /** The character value of the cluster. */ + character: string; + /** The mean of the cluster. */ + mean: BufferedCharacterItem; +} + +interface BufferedCharacterItemSet { + /** An array of BufferedCharacterItem. */ + items: Array; + /** An array of CharacterCluster. */ + characterClusters: Array; +} + +/** + * The `RawTextLine` represents a text line in an image. It can be in one of the following states: + * - `TLS_LOCALIZED`: Localized but recognition not performed. + * - `TLS_RECOGNITION_FAILED`: Recognition failed. + * - `TLS_RECOGNIZED_SUCCESSFULLY`: Successfully recognized. + */ +interface RawTextLine extends RegionObjectElement { + /** The recognized text of the line. */ + text: string; + /** Confidence score for the recognized text line. */ + confidence: number; + /** Results for individual characters within the text line. */ + characterResults: Array; + /** The row number of the text line, starting from 1. */ + rowNumber: number; + /** The predefined specification name of this text line*/ + specificationName: string; + /** The location of the text line */ + location: Quadrilateral; + /** The status of a raw text line.*/ + status: EnumRawTextLineStatus; +} + +interface RawTextLinesUnit extends IntermediateResultUnit { + /** An array of RawTextLine. */ + rawTextlines: Array; +} + +interface RecognizedTextLinesUnit extends IntermediateResultUnit { + recognizedTextLines: Array; +} + +export { BufferedCharacterItem, BufferedCharacterItemSet, CharacterCluster, CharacterResult, EnumRawTextLineStatus, LabelRecognizerModule, LocalizedTextLineElement, LocalizedTextLinesUnit, RawTextLine, RawTextLinesUnit, RecognizedTextLineElement, RecognizedTextLinesResult, RecognizedTextLinesUnit, SimplifiedLabelRecognizerSettings, TextLineResultItem, utilsFuncs }; + declare class LicenseModule { /** * Returns the version of the License module. @@ -4821,26 +5232,18 @@ declare class UtilityModule { static getVersion(): string; } -type resultItemTypesString = "barcode" | "text_line" | "detected_quad" | "deskewed_image"; +type resultItemTypesString = "barcode" | "text_line" | "detected_quad" | "deskewed_image" | "enhanced_image"; +type CapturedResultMap = { + [K in EnumCapturedResultItemType]?: T; +}; declare class MultiFrameResultCrossFilter implements CapturedResultFilter { #private; constructor(); - verificationEnabled: { - [key: number]: boolean; - }; - duplicateFilterEnabled: { - [key: number]: boolean; - }; - duplicateForgetTime: { - [key: number]: number; - }; - private latestOverlappingEnabled; - private maxOverlappingFrames; - private overlapSet; - private stabilityCount; - private crossVerificationFrames; - _dynamsoft(): void; + verificationEnabled: CapturedResultMap; + duplicateFilterEnabled: CapturedResultMap; + duplicateForgetTime: CapturedResultMap; + private _dynamsoft; /** * Enables or disables the verification of one or multiple specific result item types. * @param resultItemTypes Specifies one or multiple specific result item types, which can be defined using EnumCapturedResultItemType or a string. If using a string, only one type can be specified, and valid values include "barcode", "text_line", "detected_quad", and "normalized_image". @@ -4877,19 +5280,12 @@ declare class MultiFrameResultCrossFilter implements CapturedResultFilter { * @returns The set interval for the specified item type. */ getDuplicateForgetTime(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString): number; - /** - * Set the max referencing frames count for the to-the-latest overlapping feature. - * - * @param resultItemTypes Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". - * @param maxOverlappingFrames The max referencing frames count for the to-the-latest overlapping feature. - */ - setMaxOverlappingFrames(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, maxOverlappingFrames: number): void; - /** - * Get the max referencing frames count for the to-the-latest overlapping feature. - * @param resultItemTypes Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". - * @return Returns the max referencing frames count for the to-the-latest overlapping feature. - */ - getMaxOverlappingFrames(resultItemType: EnumCapturedResultItemType): number; + getFilteredResultItemTypes(): number; + private overlapSet; + private stabilityCount; + private crossVerificationFrames; + private latestOverlappingEnabled; + private maxOverlappingFrames; /** * Enables or disables the deduplication process for one or multiple specific result item types. * @param resultItemTypes Specifies one or multiple specific result item types, which can be defined using EnumCapturedResultItemType or a string. If using a string, only one type can be specified, and valid values include "barcode", "text_line", "detected_quad", and "normalized_image". @@ -4903,7 +5299,19 @@ declare class MultiFrameResultCrossFilter implements CapturedResultFilter { * @returns Boolean indicating the deduplication status for the specified type. */ isLatestOverlappingEnabled(resultItemType: EnumCapturedResultItemType | resultItemTypesString): boolean; - getFilteredResultItemTypes(): number; + /** + * Set the max referencing frames count for the to-the-latest overlapping feature. + * + * @param resultItemTypes Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @param maxOverlappingFrames The max referencing frames count for the to-the-latest overlapping feature. + */ + setMaxOverlappingFrames(resultItemTypes: EnumCapturedResultItemType | resultItemTypesString, maxOverlappingFrames: number): void; + /** + * Get the max referencing frames count for the to-the-latest overlapping feature. + * @param resultItemTypes Specifies the result item type, either with EnumCapturedResultItemType or a string. When using a string, the valid values include "barcode", "text_line", "detected_quad", and "normalized_image". + * @return Returns the max referencing frames count for the to-the-latest overlapping feature. + */ + getMaxOverlappingFrames(resultItemType: EnumCapturedResultItemType): number; latestOverlappingFilter(result: any): void; } diff --git a/dist/dbr.bundle.esm.js b/dist/dbr.bundle.esm.js index 23800f6..fced737 100644 --- a/dist/dbr.bundle.esm.js +++ b/dist/dbr.bundle.esm.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 11.0.6000 +* @version 11.2.2000 * @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,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function e(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function i(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const n="undefined"==typeof self,r="function"==typeof importScripts,s=(()=>{if(!r){if(!n&&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"./"}})(),o=t=>{if(null==t&&(t="./"),n||r);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var a,h,l;!function(t){t[t.SM_SINGLE=0]="SM_SINGLE",t[t.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(a||(a={})),function(t){t[t.OM_NONE=0]="OM_NONE",t[t.OM_SPEED=1]="OM_SPEED",t[t.OM_COVERAGE=2]="OM_COVERAGE",t[t.OM_BALANCE=3]="OM_BALANCE",t[t.OM_DPM=4]="OM_DPM",t[t.OM_DENSE=5]="OM_DENSE"}(h||(h={})),function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(l||(l={}));const c=t=>t&&"object"==typeof t&&"function"==typeof t.then,u=(async()=>{})().constructor;let d=class extends u{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,c(t)?e=t:"function"==typeof t&&(e=new u(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(c(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function f(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function g(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var m,p,_;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(m||(m={})),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"}(p||(p={})),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"}(_||(_={}));const v="undefined"==typeof self,y="function"==typeof importScripts,w=(()=>{if(!y){if(!v&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),C=t=>{if(null==t&&(t="./"),v||y);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},E=t=>Object.prototype.toString.call(t),S=t=>Array.isArray?Array.isArray(t):"[object Array]"===E(t),b=t=>"number"==typeof t&&!Number.isNaN(t),T=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),I=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.radius)||t.radius<0||!b(t.startAngle)||!b(t.endAngle)),x=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),O=t=>!(!T(t)||!b(t.width)||t.width<=0||!b(t.height)||t.height<=0||!b(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!L(t.tag)),R=t=>!(!O(t)||!b(t.bytes.length)&&!b(t.bytes.ptr)),A=t=>!!O(t)&&t.bytes instanceof Uint8Array,D=t=>!(!T(t)||!b(t.left)||t.left<0||!b(t.top)||t.top<0||!b(t.right)||t.right<0||!b(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),L=t=>null===t||!!T(t)&&!!b(t.imageId)&&"type"in t,M=t=>!(!T(t)||!F(t.startPoint)||!F(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),F=t=>!!T(t)&&!!b(t.x)&&!!b(t.y),P=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),k=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!F(t)),N=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.width)||t.width<0||!b(t.height)||t.height<0),B=async(t,e)=>await new Promise((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}),j=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),U=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${q[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${q[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},G=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await H(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),W=t=>{A(t)&&(t=X(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},Y=(t,e)=>{A(e)&&(e=X(e));const i=W(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},H=async(t,e)=>{A(e)&&(e=X(e));const i=W(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},X=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===_.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===_.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},z=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),q={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var K,Z,J,$,Q,tt,et,it;let nt,rt,st,ot,at,ht=class t{get _isFetchingStarted(){return f(this,Q,"f")}constructor(){K.add(this),Z.set(this,[]),J.set(this,1),$.set(this,m.BOPM_BLOCK),Q.set(this,!1),tt.set(this,void 0),et.set(this,p.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!A(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(f(this,Z,"f").length>=f(this,J,"f"))switch(f(this,$,"f")){case m.BOPM_BLOCK:break;case m.BOPM_UPDATE:if(f(this,Z,"f").push(t),T(f(this,tt,"f"))&&b(f(this,tt,"f").imageId)&&1==f(this,tt,"f").keepInBuffer)for(;f(this,Z,"f").length>f(this,J,"f");){const t=f(this,Z,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==f(this,tt,"f").imageId});f(this,Z,"f").splice(t,1)}else f(this,Z,"f").splice(0,f(this,Z,"f").length-f(this,J,"f"))}else f(this,Z,"f").push(t)}getImage(){if(0===f(this,Z,"f").length)return null;let e;if(f(this,tt,"f")&&b(f(this,tt,"f").imageId)){const t=f(this,K,"m",it).call(this,f(this,tt,"f").imageId);if(t<0)throw new Error(`Image with id ${f(this,tt,"f").imageId} doesn't exist.`);e=f(this,Z,"f").slice(t,t+1)[0]}else e=f(this,Z,"f").pop();if([_.IPF_RGB_565,_.IPF_RGB_555,_.IPF_RGB_888,_.IPF_ARGB_8888,_.IPF_RGB_161616,_.IPF_ARGB_16161616,_.IPF_ABGR_8888,_.IPF_ABGR_16161616,_.IPF_BGR_888].includes(e.format)){if(f(this,et,"f")===p.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every(t=>b(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==E(e))throw new TypeError("Invalid 'keepInBuffer'.");g(this,tt,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){g(this,tt,null,"f")}hasImage(t){return f(this,K,"m",it).call(this,t)>=0}startFetching(){g(this,Q,!0,"f")}stopFetching(){g(this,Q,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(g(this,J,t,"f");f(this,Z,"f")&&f(this,Z,"f").length>t;)f(this,Z,"f").shift()}getMaxImageCount(){return f(this,J,"f")}getImageCount(){return f(this,Z,"f").length}clearBuffer(){f(this,Z,"f").length=0}isBufferEmpty(){return 0===f(this,Z,"f").length}setBufferOverflowProtectionMode(t){g(this,$,t,"f")}getBufferOverflowProtectionMode(){return f(this,$,"f")}setColourChannelUsageType(t){g(this,et,t,"f")}getColourChannelUsageType(){return f(this,et,"f")}};Z=new WeakMap,J=new WeakMap,$=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,K=new WeakSet,it=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return f(this,Z,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(nt=navigator,rt=nt.userAgent,st=nt.platform,ot=nt.mediaDevices),function(){if(!v){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:nt.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:st,search:"Win"},Mac:{str:st},Linux:{str:st}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||rt,o=r.search||e,a=r.verStr||rt,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||rt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=rt.indexOf("Windows NT")&&(r="HarmonyOS"),at={browser:i,version:n,OS:r}}v&&(at={browser:"ssr",version:0,OS:"ssr"})}();const lt="undefined"!=typeof WebAssembly&&rt&&!(/Safari/.test(rt)&&!/Chrome/.test(rt)&&/\(.+\s11_2_([2-6]).*\)/.test(rt)),ct=!("undefined"==typeof Worker),ut=!(!ot||!ot.getUserMedia),dt=async()=>{let t=!1;if(ut)try{(await ot.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var ft,gt,mt,pt,_t,vt,yt,wt,Ct;"Chrome"===at.browser&&at.version>66||"Safari"===at.browser&&at.version>13||"OPR"===at.browser&&at.version>43||"Edge"===at.browser&&at.version,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(ft||(ft={})),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"}(gt||(gt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(mt||(mt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV",t[t.GEM_END=-1]="GEM_END"}(pt||(pt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV",t[t.GTM_END=-1]="GTM_END"}(_t||(_t={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(vt||(vt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(yt||(yt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(wt||(wt={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(Ct||(Ct={}));const Et={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var St,bt,Tt,It,xt,Ot;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(St||(St={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(bt||(bt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(Tt||(Tt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(It||(It={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(xt||(xt={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(Ot||(Ot={}));const Rt={},At=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Rt[t]=Rt[t]||new d);await Promise.all(i)},Dt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=Rt[t]=Rt[t]||new d(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let Lt,Mt=0;const Ft=()=>Mt++,Pt={};let kt;const Nt=t=>{kt=t,Lt&&Lt.postMessage({type:"setBLog",body:{value:!!t}})};let Bt=!1;const jt=t=>{Bt=t,Lt&&Lt.postMessage({type:"setBDebug",body:{value:!!t}})},Ut={},Vt={},Gt={dip:{wasm:!0}},Wt={std:{version:"2.0.0",path:C(w+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.0.60-dev-20250812165815",path:w,isInternal:!0}};class Yt{static get engineResourcePaths(){return Wt}static set engineResourcePaths(t){Object.assign(Wt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return kt}static set _onLog(t){Nt(t)}static get _bDebug(){return Bt}static set _bDebug(t){jt(t)}static get _workerName(){return`${Yt._bundleEnv.toLowerCase()}.bundle.worker.js`}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Rt[t]&&Rt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=Rt.core;e=!i||i.isEmpty,e||await At("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),xt.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||xt.MN_DYNAMSOFT_CORE==t)return;let e=Gt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=Rt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await Dt(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await At(o);const i=V(Wt),r={};for(let e of t)r[e]=Gt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:Yt._bundleEnv,_useSimd:Yt._useSimd,_useMLBackend:Yt._useMLBackend};let a=new d;if(e){s.needLoadCore=!0;let t=i[`${Yt._bundleEnv.toLowerCase()}Bundle`]+Yt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),Lt=new Worker(t),Lt.onerror=t=>{let e=new Error(t.message);a.reject(e)},Lt.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":kt&&kt(e.message);break;case"task":try{Pt[n](r),delete Pt[n]}catch(t){throw delete Pt[n],t}break;case"event":try{Pt[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!kt,s.bd=Bt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await At("core");let h=Mt++;Pt[h]=t=>{if(t.success)Object.assign(Ut,t.versions),"{}"!==JSON.stringify(t.versions)&&(Yt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},Lt.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:lt,worker:ct,getUserMedia:ut,camera:await dt(),browser:at.browser,version:at.version,OS:at.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.0.60-dev-20250812165815(Worker: ${Ut.core&&Ut.core.worker||"Not Loaded"}, Wasm: ${Ut.core&&Ut.core.wasm||"Not Loaded"})`}static enableLogging(){ht._onLog=console.log,Yt._onLog=console.log}static disableLogging(){ht._onLog=null,Yt._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cfd",id:n,body:{count:t}})})}}Yt._bSupportDce4Module=-1,Yt._bSupportIRTModule=-1,Yt._versions=null,Yt._bundleEnv="DCV",Yt._useMLBackend=!1,Yt._useSimd=!0,Yt.browserInfo=at;var Ht={license:"",scanMode:a.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:Yt.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:s,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Xt=t=>t&&"object"==typeof t&&"function"==typeof t.then,zt=(async()=>{})().constructor;class qt extends zt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xt(t)?e=t:"function"==typeof t&&(e=new zt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Xt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Kt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Zt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Jt=t=>t&&"object"==typeof t&&"function"==typeof t.then,$t=(async()=>{})().constructor;let Qt=class extends $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,Jt(t)?e=t:"function"==typeof t&&(e=new $t(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Jt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},te=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var ee={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1,onProcessedDocumentResultReceived:!1};const ie=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};let ne=class{constructor(t){this._irrRegistryState=ee,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ie(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach((t,e)=>{i[e]=t}),t._observedTaskMap.clear()}return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ie(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const re="undefined"==typeof self,se="function"==typeof importScripts,oe=(()=>{if(!se){if(!re&&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"./"}})(),ae=t=>{if(null==t&&(t="./"),re||se);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var he;Yt.engineResourcePaths.cvr={version:"3.0.60-dev-20250812165839",path:oe,isInternal:!0},Gt.cvr={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING,xt.MN_DYNAMSOFT_NEURAL_NETWORK]},Gt.dnn={wasm:!0,deps:[xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.cvr={};const le="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,le)<0&&(Yt.engineResourcePaths.std={version:le,path:ae(oe+`../../dynamsoft-capture-vision-std@${le}/dist/`),isInternal:!0});const ce="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,ce)<0)&&(Yt.engineResourcePaths.dip={version:ce,path:ae(oe+`../../dynamsoft-image-processing@${ce}/dist/`),isInternal:!0});const ue="2.0.10";(!Yt.engineResourcePaths.dnn||"string"!=typeof Yt.engineResourcePaths.dnn&&U(Yt.engineResourcePaths.dnn.version,ue)<0)&&(Yt.engineResourcePaths.dnn={version:ue,path:ae(oe+`../../dynamsoft-capture-vision-dnn@${ue}/dist/`),isInternal:!0});let de=class{static getVersion(){return this._version}};var fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le,Me,Fe,Pe,ke;function Ne(t,e){if(t&&t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Ne(t.referencedItem,e)}}function Be(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function je(t){let e=!1;const i=[mt.EC_UNSUPPORTED_JSON_KEY_WARNING,mt.EC_LICENSE_AUTH_QUOTA_EXCEEDED,mt.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}de._version=`3.0.60-dev-20250812165839(Worker: ${null===(he=Ut.cvr)||void 0===he?void 0:he.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(fe||(fe={}));const Ue={onTaskResultsReceived:()=>{},isFilter:!0};Pt[-2]=async t=>{Ve.onDataLoadProgressChanged&&Ve.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let Ve=class t{constructor(){ge.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(Yt.browserInfo.OS)?2048:4096,this.onCaptureError=null,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._dynamsoft=!0,me.set(this,null),pe.set(this,null),_e.set(this,null),ve.set(this,null),ye.set(this,null),we.set(this,new Set),Ce.set(this,new Set),Ee.set(this,new Set),Se.set(this,500),be.set(this,0),Te.set(this,0),Ie.set(this,!1),xe.set(this,!1),Oe.set(this,!1),Re.set(this,null),Ae.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Kt(this,Oe,"f")}static async createInstance(e=!0){if(!Vt.license)throw Error("The `license` module cannot be found.");await Vt.license.dynamsoft(),await Yt.loadWasm();const i=new t,n=new Qt;let r=Ft();return Pt[r]=async t=>{t.success?(i._instanceID=t.instanceID,i._currentSettings=JSON.parse(JSON.parse(t.outputSettings).data),de._version=`3.0.60-dev-20250812165839(Worker: ${Ut.cvr.worker}, Wasm: ${t.version})`,Zt(i,xe,!0,"f"),Zt(i,ve,i.getIntermediateResultManager(),"f"),Zt(i,xe,!1,"f"),n.resolve(i)):je({message:t.message,rj:n.reject,stack:t.stack,functionName:"createInstance"})},Lt.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendModelBuffer(t,e){return await Yt.loadWasm(),await new Promise((i,n)=>{let r=Ft();const s=V(Yt.engineResourcePaths);let o;Pt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&je({message:e.errorString?e.errorString:"Append Model Buffer Failed.",rj:n,errorCode:e.errorCode,functionName:"appendModelBuffer"}),i(e)}je({message:t.message,rj:n,stack:t.stack,functionName:"appendModelBuffer"})},e?o=e:"DCV"===Yt._bundleEnv?o=s.dcvData+"models/":"DBR"===Yt._bundleEnv&&(o=s.dbrBundle+"models/"),Lt.postMessage({type:"cvr_appendModelBuffer",id:r,body:{modelName:t,path:o}})})}async _singleFrameModeCallback(t){for(let e of Kt(this,we,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of Kt(this,we,"f"))t.isDce?t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}):Kt(this,ge,"m",Le).call(this,t,i)}setInput(t){if(Be(this),!t)return Kt(this,Re,"f")&&(Kt(this,ve,"f").removeResultReceiver(Kt(this,Re,"f")),Zt(this,Re,null,"f")),Kt(this,Ae,"f")&&(Kt(this,we,"f").delete(Kt(this,Ae,"f")),Zt(this,Ae,null,"f")),void Zt(this,me,null,"f");if(Zt(this,me,t,"f"),t.isCameraEnhancer){Kt(this,ve,"f")&&(Kt(this,me,"f")._intermediateResultReceiver.isDce=!0,Kt(this,ve,"f").addResultReceiver(Kt(this,me,"f")._intermediateResultReceiver),Zt(this,Re,Kt(this,me,"f")._intermediateResultReceiver,"f"));const t=Kt(this,me,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Kt(this,we,"f").add(e),Zt(this,Ae,e,"f")}}}getInput(){return Kt(this,me,"f")}addImageSourceStateListener(t){if(Be(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Kt(this,Ce,"f").add(t)}removeImageSourceStateListener(t){return Be(this),Kt(this,Ce,"f").delete(t)}addResultReceiver(t){if(Be(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Kt(this,we,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Be(this),Kt(this,we,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Kt(this,we,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Qt;let i=Ft();return Pt[i]=async t=>{t.success?e.resolve():je({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},Lt.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Be(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Kt(this,Ee,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Be(this),Kt(this,Ee,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Kt(this,ve,"f").removeResultReceiver(Ue),0===Kt(this,Ee,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},e={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1};return await Kt(this,ge,"m",Me).call(this,t),void await Kt(this,ge,"m",Fe).call(this,e)}for(let t of Kt(this,Ee,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(ft.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(ft.CRIT_BARCODE)&&([...Kt(this,ve,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Kt(this,ve,"f").addResultReceiver(Ue)),await Kt(this,ge,"m",Me).call(this,t.verificationEnabled),await Kt(this,ge,"m",Fe).call(this,t.duplicateFilterEnabled),await Kt(this,ge,"m",Pe).call(this,t.duplicateForgetTime)}async startCapturing(e){if(Be(this),!this._isPauseScan)return;if(!Kt(this,me,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);const i=await this.containsTask(e);for(let t of Kt(this,Ee,"f"))await this.addResultFilter(t);const n=V(Yt.engineResourcePaths);return Kt(this,me,"f").isCameraEnhancer&&(i.includes("ddn")?Kt(this,me,"f").setPixelFormat(_.IPF_ABGR_8888):Kt(this,me,"f").setPixelFormat(_.IPF_GRAYSCALED)),void 0!==Kt(this,me,"f").singleFrameMode&&"disabled"!==Kt(this,me,"f").singleFrameMode?(this._templateName=e,void Kt(this,me,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(Kt(this,me,"f").getColourChannelUsageType()===p.CCUT_AUTO&&Kt(this,me,"f").setColourChannelUsageType(i.includes("ddn")?p.CCUT_FULL_CHANNEL:p.CCUT_Y_CHANNEL_ONLY),Kt(this,_e,"f")&&Kt(this,_e,"f").isPending?Kt(this,_e,"f"):(Zt(this,_e,new Qt((t,i)=>{if(this.disposed)return;let r=Ft();Pt[r]=async n=>{Kt(this,_e,"f")&&!Kt(this,_e,"f").isFulfilled&&(n.success?(this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Kt(this,me,"f").startFetching(),this._loopReadVideo(e),t()},0)):je({message:n.message,rj:i,stack:n.stack,functionName:"startCapturing"}))},Lt.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:n}})}),"f"),await Kt(this,_e,"f")))}stopCapturing(){Be(this),Kt(this,me,"f")&&(Kt(this,me,"f").isCameraEnhancer&&void 0!==Kt(this,me,"f").singleFrameMode&&"disabled"!==Kt(this,me,"f").singleFrameMode?Kt(this,me,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Kt(this,ge,"m",ke).call(this),Kt(this,me,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Zt(this,_e,null,"f"),Kt(this,me,"f").setColourChannelUsageType(p.CCUT_AUTO)))}async containsTask(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));je({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},Lt.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Zt(this,Ie,!0,"f"),Kt(this,me,"f").isBufferEmpty())if(Kt(this,me,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(fe.ISS_BUFFER_EMPTY);else if(!Kt(this,me,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(fe.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Kt(this,me,"f").isBufferEmpty()&&Kt(this,me,"f").isCameraEnhancer)try{Kt(this,me,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Kt(this,me,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Kt(this,me,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Kt(this,me,"f").isCameraEnhancer&&Kt(this,me,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Kt(this,me,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Kt(this,we,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of Kt(this,we,"f"))if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}else{for(let t of Kt(this,Ee,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onProcessedDocumentResultReceived(n);Kt(this,ge,"m",Le).call(this,e,n)}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Kt(this,me,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Kt(this,me,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async capture(e,i){let n;if(Be(this),i||(i=t._defaultTemplate),Zt(this,Ie,!1,"f"),A(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await B(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Zt(this,Te,this.maxImageSideLength/o,"f"),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,pe,"f")||Zt(this,pe,document.createElement("canvas"),"f");const a=Kt(this,pe,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Zt(this,Te,this.maxImageSideLength/o,"f"),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,pe,"f")||Zt(this,pe,document.createElement("canvas"),"f");const a=Kt(this,pe,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Ft();V(Yt.engineResourcePaths);const l=new Qt;return Pt[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;t.hasOwnProperty("_needContinueProcess")&&delete t._needContinueProcess,e.bytes=i.bytes;for(let i of t.items)0!==Kt(this,Te,"f")&&Ne(i,Kt(this,Te,"f")),i.type===ft.CRIT_ORIGINAL_IMAGE?i.imageData=e:[ft.CRIT_DESKEWED_IMAGE,ft.CRIT_ENHANCED_IMAGE].includes(i.type)?Vt.ddn&&Vt.ddn.handleDeskewedAndEnhancedImageResultItem(i):i.type===ft.CRIT_PARSED_RESULT&&Vt.dcp&&Vt.dcp.handleParsedResultItem(i);const n=t.processedDocumentResult;if(n){if(n.deskewedImageResultItems)for(let t=0;tKt(this,Se,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),Zt(this,be,s,"f")),Zt(this,Te,0,"f"),l.resolve(t)}catch(i){je({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else je({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),Lt.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Kt(this,Ie,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(Be(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await B(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Ft();Pt[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&je({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}je({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},Lt.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return Be(this),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&je({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}je({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},Lt.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,null,2,function(t,e){return e instanceof Array?JSON.stringify(e):e},2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return Be(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&je({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}je({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},Lt.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return Be(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&je({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}je({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},Lt.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return Be(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&je({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}je({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},Lt.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return Be(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&je({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}je({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},Lt.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return Kt(this,ye,"f")||Zt(this,ye,new te(this),"f"),Kt(this,ye,"f")}getIntermediateResultManager(){if(Be(this),!Kt(this,xe,"f")&&0!==Yt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Kt(this,ve,"f")||Zt(this,ve,new ne(this),"f"),Kt(this,ve,"f")}async parseRequiredResources(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));je({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},Lt.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){Be(this),Kt(this,_e,"f")&&this.stopCapturing(),Zt(this,me,null,"f"),Kt(this,we,"f").clear(),Kt(this,Ce,"f").clear(),Kt(this,Ee,"f").clear(),Kt(this,ve,"f")._intermediateResultReceiverSet.clear(),Zt(this,Oe,!0,"f");let t=Ft();Pt[t]=t=>{t.success||je({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},Lt.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Kt(this,me,"f"),promiseStartScan:Kt(this,_e,"f"),intermediateResultManager:Kt(this,ve,"f"),bufferdItemsManager:Kt(this,ye,"f"),resultReceiverSet:Kt(this,we,"f"),isaStateListenerSet:Kt(this,Ce,"f"),resultFilterSet:Kt(this,Ee,"f"),compressRate:Kt(this,Te,"f"),canvas:Kt(this,pe,"f"),isScanner:Kt(this,Ie,"f"),innerUseTag:Kt(this,xe,"f"),isDestroyed:Kt(this,Oe,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}je({message:i.message,rj:e,stack:i.stack,functionName:""})},Lt.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Re=new WeakMap,Ae=new WeakMap,ge=new WeakSet,De=function(t,e){const i=t.intermediateResult;if(i){let t=0;for(let n of Kt(this,ve,"f")._intermediateResultReceiverSet){t++;for(let r of i){if(["onTaskResultsReceived","onTargetROIResultsReceived"].includes(r.info.callbackName)){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);t===Kt(this,ve,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}t&&t.hasOwnProperty("intermediateResult")&&delete t.intermediateResult},Le=function(t,e){e.decodedBarcodesResult&&t.onDecodedBarcodesReceived&&t.onDecodedBarcodesReceived(e.decodedBarcodesResult),e.recognizedTextLinesResult&&t.onRecognizedTextLinesReceived&&t.onRecognizedTextLinesReceived(e.recognizedTextLinesResult),e.processedDocumentResult&&t.onProcessedDocumentResultReceived&&t.onProcessedDocumentResultReceived(e.processedDocumentResult),e.parsedResult&&t.onParsedResultsReceived&&t.onParsedResultsReceived(e.parsedResult),t.onCapturedResultReceived&&t.onCapturedResultReceived(e)},Me=async function(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);je({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Fe=async function(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);je({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},Pe=async function(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);je({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},ke=async function(){let t=Ft();const e=new Qt;return Pt[t]=async t=>{if(t.success)return e.resolve();je({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},Lt.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},Ve._defaultTemplate="Default";let Ge=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},We=class{constructor(){this._observedResultUnitTypes=Et.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}};var Ye;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadSingleBarcode",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Ye||(Ye={}));const He="undefined"==typeof self,Xe="function"==typeof importScripts,ze=(()=>{if(!Xe){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"./"}})();Yt.engineResourcePaths.dce={version:"4.2.3-dev-20250812165927",path:ze,isInternal:!0},Gt.dce={wasm:!1,js:!1},Vt.dce={};let qe,Ke,Ze,Je,$e,Qe=class{static getVersion(){return"4.2.3-dev-20250812165927"}};function ti(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ei(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(qe=navigator,Ke=qe.userAgent,Ze=qe.platform,Je=qe.mediaDevices),function(){if(!He){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:qe.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:Ze,search:"Win"},Mac:{str:Ze},Linux:{str:Ze}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Ke,o=r.search||e,a=r.verStr||Ke,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Ke,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Ke.indexOf("Windows NT")&&(r="HarmonyOS"),$e={browser:i,version:n,OS:r}}He&&($e={browser:"ssr",version:0,OS:"ssr"})}();const ii="undefined"!=typeof WebAssembly&&Ke&&!(/Safari/.test(Ke)&&!/Chrome/.test(Ke)&&/\(.+\s11_2_([2-6]).*\)/.test(Ke)),ni=!("undefined"==typeof Worker),ri=!(!Je||!Je.getUserMedia),si=async()=>{let t=!1;if(ri)try{(await Je.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===$e.browser&&$e.version>66||"Safari"===$e.browser&&$e.version>13||"OPR"===$e.browser&&$e.version>43||"Edge"===$e.browser&&$e.version;var oi={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some(function(e){return"function"==typeof e.contains&&e.contains(t,!0)})},complexity:function(){return this._objects.reduce(function(t,e){return t+(e.complexity?e.complexity():0)},0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach(function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))}),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,I=-E*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kE)for(var T=1,I=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,R=E.length,A=R;R--;)I=(O=1-(f=E[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(function(t){for(var i=t.slice(0),n={},r=1;r=e})}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach(function(t){t.cancel()}),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter(function(e){return"object"==typeof e.target&&e.target.canvas===t});return e.forEach(function(t){t.cancel()}),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach(function(t){t.cancel()}),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find(function(e){return e.cancel===t})},findAnimationsByTarget:function(t){return t?this.filter(function(e){return e.target===t}):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map(function(t,e){return v[e]-_[e]}):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map(function(t,e){return m(n,_[e],y[e],c)}):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!o){if(!f(w,C,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",S=0,b=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=C.width-r*c,b=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y(function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach(function(e){i[e]=t[e]}),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach(function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s})}(0,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,function(t,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(e){this[e]!==i[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)},this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find(function(e){return!0===t[e]}):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach(function(i){e[i]=t[i]}),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach(function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})}),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter(function(e){return!e.onSelect({e:t})})),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){r.clear(),r._setBgOverlay(n,function(){s?r._enlivenObjects([s],function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)}):r.__setupCanvas.call(r,n,t,o,e)})},i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach(function(t,e){r.insertAt(t,e)}),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],function(e){r[t]=e[0],i[t]=!0,n&&n()}):this["set"+b.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},null,i):e&&e([])},_toDataURL:function(t,e){this.clone(function(i){e(i.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,i){this.clone(function(n){i(n.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(i,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,function(){i.renderAll(),t&&t(i)}),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach(function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])}),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var o=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,function(){var t=s?new o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,o=b.util.sin(n)*r;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach(function(t){r[t]=e[t]}),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl(function(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,function(t){delete t.points,i&&i(t)},"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r}),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter(function(t){return t&&!t.isNeutralState()}),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,function(){var n=new b.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,function(t,n){e&&e(new b.Image(t,i),n)},null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach(function(t){t.applyTo(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(b-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},ai={};function hi(t){var e=ai[t];if(void 0!==e)return e.exports;var i=ai[t]={exports:{}};return oi[t](i,i.exports,hi),i.exports}hi.d=(t,e)=>{for(var i in e)hi.o(e,i)&&!hi.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},hi.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var li={};(()=>{let t;hi.d(li,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?hi(653).fabric:{version:"5.2.1"}})();var ci,ui,di,fi,gi=li.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"}(ci||(ci={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(ui||(ui={})),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"}(di||(di={})),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"}(fi||(fi={}));const mi=t=>"number"==typeof t&&!Number.isNaN(t),pi=t=>"string"==typeof t;var _i,vi,yi,wi,Ci,Ei,Si,bi,Ti,Ii,xi;!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"}(Ci||(Ci={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(Ei||(Ei={}));let Oi=class{get mediaType(){return new Map([["rect",ci.DIMT_RECTANGLE],["quad",ci.DIMT_QUADRILATERAL],["text",ci.DIMT_TEXT],["arc",ci.DIMT_ARC],["image",ci.DIMT_IMAGE],["polygon",ci.DIMT_POLYGON],["line",ci.DIMT_LINE],["group",ci.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(ti(this,vi,"f")){case ui.DIS_DEFAULT:return"default";case ui.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"===ti(this,yi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===ti(this,yi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),ei(this,yi,t,"f")}get coordinateBase(){return ti(this,yi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(_i.add(this),vi.set(this,void 0),yi.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&&!mi(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(ui.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(ui.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(ui.DIS_SELECTED):this.setState(ui.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){ei(this,vi,t,"f")}getState(){return ti(this,vi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Li),actionName:"modifyPolygon",pointIndex:i}),t},{}),ei(this,bi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map(t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2})),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce(function(t,e,n){return t["p"+n]=new gi.Control({positionHandler:Ai,actionHandler:Mi(n>0?n-1:i,Li),actionName:"modifyPolygon",pointIndex:n}),t},{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=gi.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){ti(this,bi,"f")&&this.setPolygon(ti(this,bi,"f"))}setPolygon(t){if(!P(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 ei(this,bi,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 ti(this,bi,"f")?JSON.parse(JSON.stringify(ti(this,bi,"f"))):null}};bi=new WeakMap;let Pi=class extends Oi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return ti(this,Ii,"f")}constructor(t,e,i,n){if(super(null,n),Ti.set(this,void 0),Ii.set(this,void 0),!N(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new gi.Image(t,{left:e.x,top:e.y}));else{if(!A(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===_.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map(t=>t.split("\t")))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2})),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new gi.Control({positionHandler:Ai,actionHandler:Mi(i>0?i-1:n,Li),actionName:"modifyPolygon",pointIndex:i}),t},{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=gi.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){ti(this,Bi,"f")&&this.setLine(ti(this,Bi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!M(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 ei(this,Bi,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 ti(this,Bi,"f")?JSON.parse(JSON.stringify(ti(this,Bi,"f"))):null}}Bi=new WeakMap;let Vi=class extends Fi{constructor(t,e){if(super({points:null==t?void 0:t.points},e),ji.set(this,void 0),!k(t))throw new TypeError("Invalid 'quad'.");ei(this,ji,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){ti(this,ji,"f")&&this.setQuad(ti(this,ji,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!k(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 ei(this,ji,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 ti(this,ji,"f")?JSON.parse(JSON.stringify(ti(this,ji,"f"))):null}};ji=new WeakMap;class Gi extends Oi{constructor(t){super(new gi.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(ui.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(ui.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("deselected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map(t=>t.getDrawingItem())}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const Wi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Yi=t=>!!pi(t)&&""!==t,Hi=t=>!(!Wi(t)||"id"in t&&!mi(t.id)||"lineWidth"in t&&!mi(t.lineWidth)||"fillStyle"in t&&!Yi(t.fillStyle)||"strokeStyle"in t&&!Yi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Yi(t.fontFamily)||"fontSize"in t&&!mi(t.fontSize));class Xi{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(N(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!D(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var zi,qi;class Ki{constructor(){zi.set(this,new Map),qi.set(this,!1)}get disposed(){return ti(this,qi,"f")}on(t,e){t=t.toLowerCase();const i=ti(this,zi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else ti(this,zi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=ti(this,zi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=ti(this,zi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=ti(this,zi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){ei(this,qi,!0,"f")}}function Zi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Ji(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function $i(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}zi=new WeakMap,qi=new WeakMap;const Qi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};class tn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*r[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return tn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return tn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return tn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,br,Tr,Ir,xr,Or;class Rr{static createDrawingStyle(t){if(!Hi(t))throw new Error("Invalid style definition.");let e,i=Rr.USER_START_STYLE_ID;for(;ti(Rr,en,"f",nn).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in ti(Rr,en,"f",rn))n.hasOwnProperty(t)||(n[t]=ti(Rr,en,"f",rn)[t]);return ti(Rr,en,"f",nn).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=ti(Rr,en,"f",nn).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(ti(Rr,en,"f",nn).values())))}static _updateDrawingStyle(t,e){if(!Hi(e))throw new Error("Invalid style definition.");const i=ti(Rr,en,"f",nn).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}en=Rr,Rr.STYLE_BLUE_STROKE=1,Rr.STYLE_GREEN_STROKE=2,Rr.STYLE_ORANGE_STROKE=3,Rr.STYLE_YELLOW_STROKE=4,Rr.STYLE_BLUE_STROKE_FILL=5,Rr.STYLE_GREEN_STROKE_FILL=6,Rr.STYLE_ORANGE_STROKE_FILL=7,Rr.STYLE_YELLOW_STROKE_FILL=8,Rr.STYLE_BLUE_STROKE_TRANSPARENT=9,Rr.STYLE_GREEN_STROKE_TRANSPARENT=10,Rr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Rr.USER_START_STYLE_ID=1024,nn={value:new Map([[Rr.STYLE_BLUE_STROKE,{id:Rr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_GREEN_STROKE,{id:Rr.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}],[Rr.STYLE_ORANGE_STROKE,{id:Rr.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}],[Rr.STYLE_YELLOW_STROKE,{id:Rr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_BLUE_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_GREEN_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_ORANGE_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_YELLOW_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Rr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Rr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Rr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},rn={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&&(gi.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(gi.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),gi.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},gi.Object.prototype.transparentCorners=!1,gi.Object.prototype.cornerSize=20,gi.Object.prototype.touchCornerSize=100,gi.Object.prototype.cornerColor="rgb(254,142,20)",gi.Object.prototype.cornerStyle="circle",gi.Object.prototype.strokeUniform=!0,gi.Object.prototype.hasBorders=!1,gi.Canvas.prototype.containerClass="",gi.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=gi.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},gi.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;ii&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Ar{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 gi.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])},0)}}),e.on("before:selection:cleared",function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.fabricCanvas.id=e,this.id=e,e){case Ar.DDN_LAYER_ID:n=Rr.getDrawingStyle(Rr.STYLE_BLUE_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_BLUE_STROKE_FILL);break;case Ar.DBR_LAYER_ID:n=Rr.getDrawingStyle(Rr.STYLE_ORANGE_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_ORANGE_STROKE_FILL);break;case Ar.DLR_LAYER_ID:n=Rr.getDrawingStyle(Rr.STYLE_GREEN_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_GREEN_STROKE_FILL);break;default:n=Rr.getDrawingStyle(Rr.STYLE_YELLOW_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_YELLOW_STROKE_FILL)}for(let t of Oi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Rr.getDrawingStyle(t.styleId);return Rr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems(e=>e._mediaType===t);for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Rr.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Rr.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Rr.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Oi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Oi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Rr.getDrawingStyle(t.styleId);else{s=Rr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Oi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Rr.getDrawingStyle(t.styleId);else{s=Rr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase()):e=Oi.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Oi.arrStyleSelectors;const n=Rr.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ci.DIMT_RECTANGLE&&n.push("rect"),i&ci.DIMT_QUADRILATERAL&&n.push("quad"),i&ci.DIMT_TEXT&&n.push("text"),i&ci.DIMT_ARC&&n.push("arc"),i&ci.DIMT_IMAGE&&n.push("image"),i&ci.DIMT_POLYGON&&n.push("polygon"),i&ci.DIMT_LINE&&n.push("line");const r=[];e&ui.DIS_DEFAULT&&r.push("default"),e&ui.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Ar.DDN_LAYER_ID=1,Ar.DBR_LAYER_ID=2,Ar.DLR_LAYER_ID=3,Ar.USER_DEFINED_LAYER_BASE_ID=100,Ar.TIP_LAYER_ID=999;class Dr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Ar(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 Lr extends Ni{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),sn.set(this,void 0),on.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&ei(this,on,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},ti(this,sn,"f")),"f")}getDuration(){return ti(this,sn,"f")}}sn=new WeakMap,on=new WeakMap;class Mr{constructor(){an.add(this),hn.set(this,void 0),ln.set(this,void 0),cn.set(this,void 0),un.set(this,!0),this._drawingLayerManager=new Dr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Ar.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Ar.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()!==Ar.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(!(Wi(e=t)&&F(e.topLeftPoint)&&mi(e.width))||e.width<=0||!mi(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;ei(this,hn,JSON.parse(JSON.stringify(t)),"f"),ti(this,hn,"f").coordinateBase||(ti(this,hn,"f").coordinateBase="view"),ei(this,cn,t.duration,"f"),ti(this,an,"m",mn).call(this)}getTipConfig(){return ti(this,hn,"f")?ti(this,hn,"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()),ei(this,un,t,"f")}isTipVisible(){return ti(this,un,"f")}updateTipMessage(t){if(!ti(this,hn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Rr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Ar.TIP_LAYER_ID)||this._createDrawingLayer(Ar.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=ti(this,an,"m",dn).call(this,t,ti(this,hn,"f").topLeftPoint.x,ti(this,hn,"f").topLeftPoint.y,ti(this,hn,"f").width,ti(this,hn,"f").coordinateBase,this._tipStyleId),ti(this,an,"m",fn).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",ti(this,un,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),ti(this,ln,"f")&&clearTimeout(ti(this,ln,"f")),ti(this,cn,"f")>=0&&ei(this,ln,setTimeout(()=>{ti(this,an,"m",gn).call(this)},ti(this,cn,"f")),"f")}}hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,an=new WeakSet,dn=function(t,e,i,n,r,s){const o=new Lr(t,e,i,n,s);return o.coordinateBase=r,o},fn=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},gn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},mn=function(){if(!this._tip)return;const t=ti(this,hn,"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 Fr extends HTMLElement{constructor(){super(),pn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),ei(this,pn,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return ti(this,pn,"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())}}pn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Fr);class Pr extends Mr{static get engineResourcePath(){const t=V(Yt.engineResourcePaths);return"DCV"===Yt._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Pr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Pr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Pr.engineResourcePath)}static async createInstance(t){const e=new Pr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Pr.engineResourcePath)),await e.setUIElement(t||Pr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==ti(this,In,"f")){if(ei(this,In,t,"f"),ti(this,_n,"m",Rn).call(this))ei(this,Cn,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"),!ti(this,Cn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes($e.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ei(this,Cn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}ti(this,_n,"m",Rn).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 ti(this,In,"f")}get disposed(){return ti(this,On,"f")}constructor(){super(),_n.add(this),vn.set(this,void 0),yn.set(this,void 0),wn.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",Cn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._poweredBy=null,En.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Sn.set(this,!1),bn.set(this,!1),Tn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{ti(this,_n,"m",Fn).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()&&ti(this,_n,"m",Mn).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Pr._onLog&&Pr._onLog("window resize event triggered."),ti(this,Tn,"f").width===document.documentElement.clientWidth&&ti(this,Tn,"f").height===document.documentElement.clientHeight||(ti(this,Tn,"f").width=document.documentElement.clientWidth,ti(this,Tn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},In.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!ti(this,_n,"m",Rn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout(()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)},0)}),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},xn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach(t=>Pr._transformCoordinates(t,i,n,r,s,o,a));const c=new Vi({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]),ti(this,xn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case ft.CRIT_ORIGINAL_IMAGE:break;case ft.CRIT_BARCODE:m=this.getDrawingLayer(Ar.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,Rr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_TEXT_LINE:m=this.getDrawingLayer(Ar.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,Rr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Ar.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Rr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case ft.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(Ar.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Rr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case ft.CRIT_PARSED_RESULT:case ft.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}if(t.decodedBarcodesResult)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f));if(t.recognizedTextLinesResult)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult){if(t.processedDocumentResult.detectedQuadResultItems)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult.deskewedImageResultItems)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f))}}},On.set(this,!1),this.eventHandler=new Ki,this.eventHandler.on("content:updated",()=>{ti(this,vn,"f")&&clearTimeout(ti(this,vn,"f")),ei(this,vn,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",()=>{ti(this,yn,"f")&&clearTimeout(ti(this,yn,"f")),ei(this,yn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),ti(this,_n,"m",Rn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes($e.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ei(this,Cn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||ti(this,_n,"m",Rn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||ti(this,_n,"m",Rn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||ti(this,_n,"m",Fn).call(this),ti(this,_n,"m",Rn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),ti(this,_n,"m",Rn).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;Pr._onLog&&Pr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()}));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}ti(this,Tn,"f").width=document.documentElement.clientWidth,ti(this,Tn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;ti(this,_n,"m",Rn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),ti(this,_n,"m",Fn).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,ei(this,Cn,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return ti(this,Cn,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!ti(this,Cn,"f"))return;if(ti(this,Cn,"f").style.objectFit=t,ti(this,_n,"m",Rn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();ti(this,_n,"m",Pn).call(this,e,i),ti(this,_n,"m",An).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(ti(this,_n,"m",Rn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=ti(this,Cn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=ti(this,Cn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){D(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):N(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=Xi.convert(this.scanRegion,t.width,t.height,this);ei(this,En,e,"f"),ti(this,wn,"f")&&clearTimeout(ti(this,wn,"f")),ei(this,wn,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}ti(this,_n,"m",An).call(this,t,e),ti(this,_n,"m",Pn).call(this,t,e)},0),"f")}getConvertedRegion(){return ti(this,En,"f")}setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=ti(this,Cn,"f").videoWidth,i=ti(this,Cn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=ti(this,Cn,"f").videoWidth,e=ti(this,Cn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove()),ti(this,xn,"f").length=0}dispose(){this._unbindUI(),ei(this,On,!0,"f")}}vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Sn=new WeakMap,bn=new WeakMap,Tn=new WeakMap,In=new WeakMap,xn=new WeakMap,On=new WeakMap,_n=new WeakSet,Rn=function(){return"disabled"!==this._singleFrameMode},An=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)},Dn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Ln=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Mn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Fn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Pn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach(e=>t.attachShader(i,e)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);ei(this,Bn,{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"),ei(this,jn,e(t),"f"),ei(this,Nn,i(t),"f"),ei(this,kn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,o,m)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[fi.GREY,fi.GREY32].includes(p)?1:0);let _,v,y=tn.translate(tn.identity(),-1,-1);y=tn.scale(y,2,2),y=tn.scale(y,1/t.canvas.width,1/t.canvas.height),_=tn.translate(y,u,d),_=tn.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=tn.translate(tn.identity(),1,0),v=tn.scale(v,-1,1),v=tn.translate(v,a/i,h/n),v=tn.scale(v,l/i,c/n)):(v=tn.translate(tn.identity(),a/i,h/n),v=tn.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,ti(this,Nn,"f"),e),y(t,ti(this,Bn,"f"),ti(this,jn,"f"),ti(this,Nn,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){kr._onLog&&kr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return kr._onLog&&kr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===fi.GREY?fi.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return kr._onLog&&kr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(kr._onLog&&(r=Date.now(),kr._onLog("transformPixelFormat(), START: "+r)),e===i)return kr._onLog&&kr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[fi.RGBA,fi.RBGA,fi.GRBA,fi.GBRA,fi.BRGA,fi.BGRA];if(o.includes(e))if(i===fi.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=kr._onLog)||void 0===n||n.call(kr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||fi.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(fi.GREY===y&&w.length{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Br{static get version(){return"4.2.3-dev-20250812165927"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find(t=>e.includes(t.label.toLowerCase()));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!r.length)return null;const s=r.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(s)return s.deviceId;const o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes($e.OS))return Br.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($e.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise(async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise(t=>{g=t}),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise(t=>{setTimeout(t,1e3)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}})}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!ti(this,er,"f"))return"closed";if("pending"===ti(this,er,"f"))return"opening";if("fulfilled"===ti(this,er,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Br.isStorageAvailable("localStorage")?ei(this,Jn,!0,"f"):(ei(this,Jn,!1,"f"),console.warn("Local storage is unavailable")):ei(this,Jn,!1,"f")}get ifSaveLastUsedCamera(){return ti(this,Jn,"f")}get isVideoPlaying(){return!(!ti(this,Yn,"f")||ti(this,Yn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=ti(this,ar,"f"))||void 0===e||e.removeEventListener("click",ti(this,or,"f")),null===(i=ti(this,ar,"f"))||void 0===i||i.removeEventListener("touchend",ti(this,or,"f")),null===(n=ti(this,ar,"f"))||void 0===n||n.removeEventListener("touchmove",ti(this,sr,"f")),ei(this,ar,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes($e.OS)?(t.addEventListener("touchend",ti(this,or,"f")),t.addEventListener("touchmove",ti(this,sr,"f"))):t.addEventListener("click",ti(this,or,"f")))}get tapFocusEventBoundEl(){return ti(this,ar,"f")}get disposed(){return ti(this,pr,"f")}constructor(t){var e,i;Wn.add(this),Yn.set(this,null),Hn.set(this,void 0),this._zoomPreSetting=null,Xn.set(this,()=>{"opened"===this.state&&ti(this,ur,"f").fire("resumed",null,{target:this,async:!1})}),zn.set(this,()=>{ti(this,ur,"f").fire("paused",null,{target:this,async:!1})}),qn.set(this,void 0),Kn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Zn.set(this,void 0),Jn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,$n.set(this,void 0),Qn.set(this,!0),tr.set(this,void 0),er.set(this,void 0),ir.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},nr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(ti(this,Yn,"f")).objectFit,s=this.getResolution(),o=ti(this,Yn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=ti(this,Yn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},rr.set(this,!1),sr.set(this,()=>{ei(this,rr,!0,"f")}),or.set(this,async t=>{var e;if(ti(this,rr,"f"))return void ei(this,rr,!1,"f");if(!ti(this,nr,"f"))return;if(!this.isVideoPlaying)return;if(!ti(this,Hn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Br._onLog&&(c=Date.now());try{await ti(this,Wn,"m",Ir).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Br._onLog)throw Br._onLog(t),t}Br._onLog&&Br._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Br._onLog&&Br._onLog("Back to continuous focus."),null===(t=ti(this,Hn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),ti(this,ur,"f").fire("tapfocus",null,{target:this,async:!1})}),ar.set(this,null),hr.set(this,1),lr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!ti(this,Yn,"f"))return;const t=ti(this,hr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)ti(this,Yn,"f").style.transform="";else{const e=window.getComputedStyle(ti(this,Yn,"f")).objectFit,i=ti(this,Yn,"f").videoWidth,n=ti(this,Yn,"f").videoHeight,{width:r,height:s}=ti(this,Yn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-ti(this,lr,"f").x),c=h*(1-1/t)*(n/2-ti(this,lr,"f").y);ti(this,Yn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},cr.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===fi.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Br._onLog&&Br._onLog("document visible. video paused: "+(null===(t=ti(this,Yn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Br._onLog&&Br._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Br._onLog&&Br._onLog("document visible. 1st resume video failed, try open instead.")}e||await ti(this,Wn,"m",Cr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Br._onLog&&Br._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Br._onLog&&Br._onLog("document visible. 2rd resume video failed, try open instead.")}e||await ti(this,Wn,"m",Cr).call(this)}}}else"hidden"===document.visibilityState&&(Br._onLog&&Br._onLog("document hidden. video paused: "+(null===(e=ti(this,Yn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),pr.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(()=>{Br.onWarning&&Br.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),ei(this,ur,new Ki,"f"),this.imageDataGetter=new kr,document.addEventListener("visibilitychange",ti(this,mr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",ti(this,Xn,"f")),t.addEventListener("pause",ti(this,zn,"f")),ei(this,Yn,t,"f")}getVideoEl(){return ti(this,Yn,"f")}releaseVideoEl(){var t,e;null===(t=ti(this,Yn,"f"))||void 0===t||t.removeEventListener("play",ti(this,Xn,"f")),null===(e=ti(this,Yn,"f"))||void 0===e||e.removeEventListener("pause",ti(this,zn,"f")),ei(this,Yn,null,"f")}isVideoLoaded(){return!!ti(this,Yn,"f")&&(this.videoSrc?0!==ti(this,Yn,"f").readyState:4===ti(this,Yn,"f").readyState)}async open(){if(ti(this,tr,"f")&&!ti(this,Qn,"f")){if("pending"===ti(this,er,"f"))return ti(this,tr,"f");if("fulfilled"===ti(this,er,"f"))return}ti(this,ur,"f").fire("before:open",null,{target:this}),await ti(this,Wn,"m",Cr).call(this),ti(this,ur,"f").fire("played",null,{target:this,async:!1}),ti(this,ur,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;ti(this,ur,"f").fire("before:close",null,{target:this});const t=ti(this,tr,"f");if(ti(this,Wn,"m",Sr).call(this),t&&"pending"===ti(this,er,"f")){try{await t}catch(t){}if(!1===ti(this,Qn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}ei(this,tr,null,"f"),ei(this,er,null,"f"),ti(this,ur,"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.");ti(this,Yn,"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 ti(this,Yn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof ti(this,qn,"f").video&&(ti(this,qn,"f").video={}),delete ti(this,qn,"f").video.facingMode,ti(this,qn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&ti(this,Qn,"f"))){ti(this,ur,"f").fire("before:camera:change",[],{target:this,async:!1}),await ti(this,Wn,"m",Er).call(this);try{this.resetSoftwareScale()}catch(t){}return ti(this,Kn,"f")}}async switchToFrontCamera(t){if("object"!=typeof ti(this,qn,"f").video&&(ti(this,qn,"f").video={}),(null==t?void 0:t.resolution)&&(ti(this,qn,"f").video.width={ideal:t.resolution.width},ti(this,qn,"f").video.height={ideal:t.resolution.height}),delete ti(this,qn,"f").video.deviceId,ti(this,qn,"f").video.facingMode={exact:"user"},ei(this,Zn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&ti(this,Qn,"f"))){ti(this,ur,"f").fire("before:camera:change",[],{target:this,async:!1}),ti(this,Wn,"m",Er).call(this);try{this.resetSoftwareScale()}catch(t){}return ti(this,Kn,"f")}}getCamera(){var t;if(ti(this,Kn,"f"))return ti(this,Kn,"f");{let e=(null===(t=ti(this,qn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"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 ti(this,qn,"f").video&&(ti(this,qn,"f").video={}),i?(ti(this,qn,"f").video.width={exact:t},ti(this,qn,"f").video.height={exact:e}):(ti(this,qn,"f").video.width={ideal:t},ti(this,qn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&ti(this,Qn,"f"))return null;ti(this,ur,"f").fire("before:resolution:change",[],{target:this,async:!1}),await ti(this,Wn,"m",Er).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&ti(this,Yn,"f"))return{width:ti(this,Yn,"f").videoWidth,height:ti(this,Yn,"f").videoHeight};if(ti(this,Hn,"f")){const t=ti(this,Hn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:ti(this,Yn,"f").videoWidth,height:ti(this,Yn,"f").videoHeight};{const t={width:0,height:0};let e=ti(this,qn,"f").video.width||0,i=ti(this,qn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=ti(this,fr,"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=ti(this,Kn,"f"))||void 0===u?void 0:u.deviceId;let e=ti(this,fr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],ti(this,fr,"f").set(d,e),ei(this,ir,!0,"f");try{for(let t of this.detectedResolutions){await ti(this,Hn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),ti(this,Wn,"m",vr).call(this);const i=ti(this,Hn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw ti(this,Wn,"m",Sr).call(this),ei(this,ir,!1,"f"),t}try{await ti(this,Wn,"m",Cr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{ei(this,ir,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=ti(this,qn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=ti(this,qn,"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=ti(this,qn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=ti(this,fr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],ti(this,fr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");ei(this,qn,JSON.parse(JSON.stringify(t)),"f"),ei(this,Zn,null,"f"),e&&await ti(this,Wn,"m",Er).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(ti(this,qn,"f")))}resetMediaStreamConstraints(){ei(this,qn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ti(this,Hn,"f").getCapabilities?ti(this,Hn,"f").getCapabilities():{}}getCameraSettings(){if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ti(this,Hn,"f").getSettings()}async turnOnTorch(){if(!ti(this,Hn,"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 ti(this,Hn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!ti(this,Hn,"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 ti(this,Hn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await ti(this,Hn,"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(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await ti(this,Hn,"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(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await ti(this,Hn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Nr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await ti(this,Hn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await ti(this,Wn,"m",Ir).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await ti(this,Hn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}enableTapToFocus(){ei(this,nr,!0,"f")}disableTapToFocus(){ei(this,nr,!1,"f")}isTapToFocusEnabled(){return ti(this,nr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"===this.state){t.centerPoint?ti(this,Wn,"m",xr).call(this,t.centerPoint):this.resetScaleCenter();try{if(ti(this,Wn,"m",Or).call(this,ti(this,lr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}else this._zoomPreSetting=t}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*ti(this,hr,"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(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await ti(this,Hn,"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&&ti(this,Wn,"m",xr).call(this,e),ei(this,hr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return ti(this,hr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();ei(this,lr,{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(ti(this,ir,"f"))return null;const e=Date.now();Br._onLog&&Br._onLog("getFrameData() START: "+e);const i=ti(this,Yn,"f").videoWidth,n=ti(this,Yn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=fi.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=ti(this,hr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=ti(this,lr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(ti(this,Yn,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Br._onLog&&Br._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:ti(this,cr,"f")}}on(t,e){if(!ti(this,dr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);ti(this,ur,"f").on(t,e)}off(t,e){ti(this,ur,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),ti(this,ur,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",ti(this,mr,"f")),ei(this,pr,!0,"f")}}var jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws;Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,Wn=new WeakSet,_r=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(ti(this,Zn,"f"))delete t.video.facingMode,t.video.deviceId={exact:ti(this,Zn,"f")};else if(this.ifSaveLastUsedCamera&&Br.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($e.OS)?(await this._getCameras(!1),ti(this,Wn,"m",vr).call(this),e=Br.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes($e.OS)||(await this._getCameras(!1),ti(this,Wn,"m",vr).call(this),e=Br.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},vr=function(){if(ti(this,Qn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},yr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Br._onLog&&Br._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise(t=>setTimeout(t,r)),ti(this,Wn,"m",vr).call(this));try{Br._onLog&&Br._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),ti(this,Wn,"m",vr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Br._onLog&&Br._onLog(t.message||t)}}};if(await r(t),!n&&"object"==typeof t.video&&(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t)),!n)){const t=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let e of t){const t={video:{deviceId:{ideal:e.deviceId},facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}}};if(await r(t),n)break}}if(!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach(t=>{t.stop()}),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},wr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),ei(this,Hn,null,"f")},Cr=async function(){ei(this,Qn,!1,"f");const t=ei(this,$n,Symbol(),"f");if(ti(this,tr,"f")&&"pending"===ti(this,er,"f")){try{await ti(this,tr,"f")}catch(t){}ti(this,Wn,"m",vr).call(this)}if(t!==ti(this,$n,"f"))return;const e=ei(this,tr,(async()=>{ei(this,er,"pending","f");try{if(this.videoSrc){if(!ti(this,Yn,"f"))throw new Error("'videoEl' should be set.");await Br.playVideo(ti(this,Yn,"f"),this.videoSrc,this.cameraOpenTimeout),ti(this,Wn,"m",vr).call(this)}else{let t=await ti(this,Wn,"m",_r).call(this);ti(this,Wn,"m",wr).call(this);let e=await ti(this,Wn,"m",yr).call(this,t);await this._getCameras(!1),ti(this,Wn,"m",vr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=ti(this,qn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(ti(this,Zn,"f")||this.ifSaveLastUsedCamera&&Br.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Br.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:s},e=await ti(this,Wn,"m",yr).call(this,t),ti(this,Wn,"m",vr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(ei(this,Zn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Br.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",ti(this,Zn,"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))))),ti(this,Yn,"f")&&(await Br.playVideo(ti(this,Yn,"f"),e,this.cameraOpenTimeout),ti(this,Wn,"m",vr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&ei(this,Hn,s[0],"f"),ei(this,Kn,r,"f")}}catch(t){throw ti(this,Wn,"m",Sr).call(this),ei(this,er,null,"f"),t}ei(this,er,"fulfilled","f")})(),"f");return e},Er=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=ti(this,Kn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await ti(this,Wn,"m",Cr).call(this);const n=this.getResolution();e&&e!==ti(this,Kn,"f").deviceId&&ti(this,ur,"f").fire("camera:changed",[ti(this,Kn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||ti(this,ur,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),ti(this,ur,"f").fire("played",null,{target:this,async:!1})},Sr=function(){ti(this,Wn,"m",wr).call(this),ei(this,Kn,null,"f"),ti(this,Yn,"f")&&(ti(this,Yn,"f").srcObject=null,this.videoSrc&&(ti(this,Yn,"f").pause(),ti(this,Yn,"f").currentTime=0)),ei(this,Qn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},br=async function t(e,i){const n=t=>{if(!ti(this,Hn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){ti(this,Hn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Nr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await ti(this,Hn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise(t=>{setTimeout(t,r)}),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(ti(this,Yn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:fi.RGBA,bufferContainer:d}))return ti(this,Wn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await ti(this,Wn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await ti(this,Wn,"m",br).call(this,e,c);if(a>h)return await ti(this,Wn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await ti(this,Wn,"m",t).call(this,e,o,a,c,h);let u=await ti(this,Wn,"m",br).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!==ti(this,hr,"f")){const t=ti(this,hr,"f"),e=ti(this,lr,"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 n=Nr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Nr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Nr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await ti(this,Wn,"m",br).call(this,t,s),a=await ti(this,Wn,"m",br).call(this,t,r),h=await ti(this,Wn,"m",br).call(this,t,n);if(a>h&&ho&&a>o){let e=await ti(this,Wn,"m",br).call(this,t,i);const r=await ti(this,Wn,"m",Tr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await ti(this,Wn,"m",Tr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},xr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");ei(this,lr,{x:i,y:n},"f")},Or=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},Br.browserInfo=$e,Br.onWarning=null===(Gn=null===window||void 0===window?void 0:window.console)||void 0===Gn?void 0:Gn.warn;class Cs{constructor(t){jr.add(this),Ur.set(this,void 0),Vr.set(this,0),Gr.set(this,void 0),Wr.set(this,0),Yr.set(this,!1),ei(this,Ur,t,"f")}startCharging(){ti(this,Yr,"f")||(Cs._onLog&&Cs._onLog("start charging."),ti(this,jr,"m",Xr).call(this),ei(this,Yr,!0,"f"))}stopCharging(){ti(this,Gr,"f")&&clearTimeout(ti(this,Gr,"f")),ti(this,Yr,"f")&&(Cs._onLog&&Cs._onLog("stop charging."),ei(this,Vr,Date.now()-ti(this,Wr,"f"),"f"),ei(this,Yr,!1,"f"))}}Ur=new WeakMap,Vr=new WeakMap,Gr=new WeakMap,Wr=new WeakMap,Yr=new WeakMap,jr=new WeakSet,Hr=function(){Yt.cfd(1),Cs._onLog&&Cs._onLog("charge 1.")},Xr=function t(){0==ti(this,Vr,"f")&&ti(this,jr,"m",Hr).call(this),ei(this,Wr,Date.now(),"f"),ti(this,Gr,"f")&&clearTimeout(ti(this,Gr,"f")),ei(this,Gr,setTimeout(()=>{ei(this,Vr,0,"f"),ti(this,jr,"m",t).call(this)},ti(this,Ur,"f")-ti(this,Vr,"f")),"f")};class Es{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-ti(this,zr,"f",Zr)<100)){if(ei(this,zr,e,"f",Zr),ti(this,zr,"f",qr).size&&(t=ti(this,zr,"f",qr).values().next().value,this.beepSoundSource==t.src?(ti(this,zr,"f",qr).delete(t),t.play()):t=null),!t)if(ti(this,zr,"f",Kr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{ti(this,zr,"f",Kr).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,ti(this,zr,"f",Kr).delete(t),ti(this,zr,"f",qr).add(t)})}else ti(this,zr,"f",Jr)||(ei(this,zr,!0,"f",Jr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&ti(this,zr,"f",Kr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Es.vibrateDuration)}}}zr=Es,qr={value:new Set},Kr={value:new Set},Zr={value:0},Jr={value:!1},Es.allowBeep=!0,Es.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Es.allowVibrate=!0,Es.vibrateDuration=300;const Ss=new Map([[fi.GREY,_.IPF_GRAYSCALED],[fi.RGBA,_.IPF_ABGR_8888]]),bs="function"==typeof BigInt?t=>BigInt(t):t=>t,Ts=(bs("0x00"),bs("0xFFFFFFFFFFFFFFFF"),bs("0xFE3BFFFF"),bs("0x003007FF")),Is=(bs("0x0003F800"),bs("0x1"),bs("0x2"),bs("0x4"),bs("0x8"),bs("0x10"),bs("0x20"),bs("0x40"),bs("0x80"),bs("0x100"),bs("0x200"),bs("0x400"),bs("0x800"),bs("0x1000"),bs("0x2000"),bs("0x4000"),bs("0x8000"),bs("0x10000"),bs("0x20000"),bs("0x00040000"),bs("0x01000000"),bs("0x02000000"),bs("0x04000000")),xs=bs("0x08000000");bs("0x10000000"),bs("0x20000000"),bs("0x40000000"),bs("0x00080000"),bs("0x80000000"),bs("0x100000"),bs("0x200000"),bs("0x400000"),bs("0x800000"),bs("0x1000000000"),bs("0x3F0000000000000"),bs("0x100000000"),bs("0x10000000000000"),bs("0x20000000000000"),bs("0x40000000000000"),bs("0x80000000000000"),bs("0x100000000000000"),bs("0x200000000000000"),bs("0x200000000"),bs("0x400000000"),bs("0x800000000"),bs("0xC00000000"),bs("0x2000000000"),bs("0x4000000000");class Os extends ht{static set _onLog(t){ei(Os,Qr,t,"f",ts),Br._onLog=t,Cs._onLog=t}static get _onLog(){return ti(Os,Qr,"f",ts)}static async detectEnvironment(){return await(async()=>({wasm:ii,worker:ni,getUserMedia:ri,camera:await si(),browser:$e.browser,version:$e.version,OS:$e.OS}))()}static async testCameraAccess(){const t=await Br.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 Pr))throw new TypeError("Invalid view.");if(!Os._isRTU&&(null===(e=Vt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=Vt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await Yt.loadWasm(),await Vt.license.dynamsoft()}const n=new Os(t);return Os.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{Os.onWarning&&Os.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(()=>{Os.onWarning&&Os.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})},0)),n}get isEnableMirroring(){return this._isEnableMirroring}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");ei(this,rs,t,"f")}get singleFrameMode(){return ti(this,rs,"f")}get _isFetchingStarted(){return ti(this,cs,"f")}get disposed(){return ti(this,ms,"f")}constructor(t){if(super(),$r.add(this),es.set(this,"closed"),is.set(this,void 0),ns.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,rs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ss.set(this,(t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?fi.GREY:fi.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===fi.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:Ss.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:ti(this,os,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Xi.convert(ti(this,hs,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=ti(this,ss,"f").call(this,t,t.width,t.height,e);ti(this,is,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},os.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===_.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes($e.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",()=>{ti(this,gs,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("camera:changed",()=>{this.clearBuffer()}),this._on("before:resolution:change",()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("resolution:changed",()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})}),this._on("paused",()=>{ti(this,gs,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{ti(this,ds,"f").tapToFocus&&ti(this,gs,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(ti(this,$r,"m",ps).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Os._onLog&&(Os._onLog("intermediateResultUnits:"),Os._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Et.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Et.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Os._onLog&&(Os._onLog("hasLocalizedBarcodes:"),Os._onLog(h)),ti(this,ds,"f").autoZoom||ti(this,ds,"f").enhancedFocus)if(a)ti(this,fs,"f").autoZoomInFrameArray.length=0,ti(this,fs,"f").autoZoomOutFrameCount=0,ti(this,fs,"f").frameArrayInIdealZoom.length=0,ti(this,fs,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),ti(this,ds,"f").autoZoom&&ti(this,gs,"f").startCharging()},a=async t=>{await this.setFocus(t),ti(this,ds,"f").enhancedFocus&&ti(this,gs,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-ti(this,fs,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+ti(this,fs,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-ti(this,fs,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+ti(this,fs,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Os._onLog&&(Os._onLog("detectionArea:"),Os._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Ji(a.y-i)>0&&Ji(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!($i([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||$i([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||$i([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||$i([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Pr._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Os._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Rr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Fi({points:i},e);t.addDrawingItems([r])}}}if(Os._onLog&&(Os._onLog("intersectedResults:"),Os._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==Is||t.possibleFormats==xs);if(t.length||(t=s.filter(t=>t.possibleFormats==Ts),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{}),ti(this,fs,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=ti(this,fs,"f").autoZoomInFrameLimit[1]){ti(this,fs,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,ti(this,fs,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/ti(this,fs,"f").autoZoomInMaxTimes),ti(this,fs,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(ti(this,fs,"f").minValue,u),u=Math.min(ti(this,fs,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(ti(this,fs,"f").autoZoomInFrameArray.length=0,ti(this,fs,"f").frameArrayInIdealZoom.push(!0),ti(this,fs,"f").frameArrayInIdealZoom.splice(0,ti(this,fs,"f").frameArrayInIdealZoom.length-ti(this,fs,"f").frameLimitInIdealZoom[0]),ti(this,fs,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=ti(this,fs,"f").frameLimitInIdealZoom[1]&&(ti(this,fs,"f").frameArrayInIdealZoom.length=0,ti(this,ds,"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(!ti(this,ds,"f").autoZoom&&ti(this,ds,"f").enhancedFocus&&(ti(this,fs,"f").autoFocusFrameArray.push(!0),ti(this,fs,"f").autoFocusFrameArray.splice(0,ti(this,fs,"f").autoFocusFrameArray.length-ti(this,fs,"f").autoFocusFrameLimit[0]),ti(this,fs,"f").autoFocusFrameArray.filter(t=>!0===t).length>=ti(this,fs,"f").autoFocusFrameLimit[1])){ti(this,fs,"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(ti(this,ds,"f").autoZoom){if(ti(this,fs,"f").autoZoomInFrameArray.push(!1),ti(this,fs,"f").autoZoomInFrameArray.splice(0,ti(this,fs,"f").autoZoomInFrameArray.length-ti(this,fs,"f").autoZoomInFrameLimit[0]),ti(this,fs,"f").autoZoomOutFrameCount++,ti(this,fs,"f").frameArrayInIdealZoom.push(!1),ti(this,fs,"f").frameArrayInIdealZoom.splice(0,ti(this,fs,"f").frameArrayInIdealZoom.length-ti(this,fs,"f").frameLimitInIdealZoom[0]),ti(this,fs,"f").autoZoomOutFrameCount>=ti(this,fs,"f").autoZoomOutFrameLimit){ti(this,fs,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*ti(this,fs,"f").autoZoomOutStepRate,ti(this,fs,"f").autoZoomOutMinStep);n=Math.max(ti(this,fs,"f").minValue,n),n=Math.min(ti(this,fs,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}ti(this,ds,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!ti(this,ds,"f").autoZoom&&ti(this,ds,"f").enhancedFocus&&(ti(this,fs,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},ei(this,gs,new Cs(1e4),"f")}setCameraView(t){if(!(t instanceof Pr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),ti(this,$r,"m",ps).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;ti(this,$r,"m",ps).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return ti(this,$r,"m",ps).call(this)?ti(this,es,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,ti(this,$r,"m",ps).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(ti(this,$r,"m",ps).call(this));else{try{await this.cameraManager.open(),ei(this,ns,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=Es.allowBeep?"":"none"),a&&(a.style.display=Es.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=Es.allowVibrate?"":"none"),l&&(l.style.display=Es.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const C=()=>{Es.allowBeep=!Es.allowBeep,o&&(o.style.display=Es.allowBeep?"":"none"),a&&(a.style.display=Es.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",C);const E=()=>{Es.allowVibrate=!Es.allowVibrate,h&&(h.style.display=Es.allowVibrate?"":"none"),l&&(l.style.display=Es.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",E);const S=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==$e?void 0:$e.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",C);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",E);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return ei(this,es,"open","f"),e&&(e._innerComponent.style.display="",ti(this,$r,"m",ps).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),ti(this,is,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),ti(this,$r,"m",ps).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}ei(this,es,"closed","f"),ti(this,gs,"f").stopCharging(),e&&(e._innerComponent.style.display="none",ti(this,$r,"m",ps).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),ti(this,is,"f").fire("closed",null,{target:this,async:!1})}pause(){if(ti(this,$r,"m",ps).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!ti(this,$r,"m",ps).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(ti(this,$r,"m",ps).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch(()=>{});const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),this.toggleMirroring(this._isEnableMirroring),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ti(this,is,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ti(this,is,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(ti(this,$r,"m",ps).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(ti(this,$r,"m",ps).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(_.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Os._onLog)||void 0===t||t.call(Os,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(ti(this,$r,"m",ps).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(ti(this,$r,"m",ps).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(ti(this,$r,"m",ps).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(ti(this,$r,"m",ps).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(ti(this,$r,"m",ps).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(ti(this,$r,"m",ps).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){ti(this,fs,"f").minValue=t.min,ti(this,fs,"f").maxValue=t.max}getAutoZoomRange(){return{min:ti(this,fs,"f").minValue,max:ti(this,fs,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=Vt.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!==Yt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&di.EF_ENHANCED_FOCUS&&(ti(this,ds,"f").enhancedFocus=!0),t&di.EF_AUTO_ZOOM&&(ti(this,ds,"f").autoZoom=!0),t&di.EF_TAP_TO_FOCUS&&(ti(this,ds,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&di.EF_ENHANCED_FOCUS&&(ti(this,ds,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&di.EF_AUTO_ZOOM&&(ti(this,ds,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&di.EF_TAP_TO_FOCUS&&(ti(this,ds,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),ti(this,$r,"m",vs).call(this)&&ti(this,$r,"m",_s).call(this)||ti(this,gs,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");ei(this,hs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(ti(this,hs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");ei(this,as,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||ti(this,$r,"m",ps).call(this))}startFetching(){if(ti(this,$r,"m",ps).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");ti(this,cs,"f")||(ei(this,cs,!0,"f"),ti(this,$r,"m",ys).call(this))}stopFetching(){ti(this,cs,"f")&&(Os._onLog&&Os._onLog("DCE: stop fetching loop: "+Date.now()),ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),ei(this,cs,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(ti(this,$r,"m",ps).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i;if(i=Xi.convert(ti(this,hs,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y);const n=this.cameraView.regionMaskLineWidth;let r;r=ti(this,hs,"f")&&!t?{sx:i.x+n,sy:i.y+n,sWidth:i.width-2*n,sHeight:i.height-2*n,dWidth:i.width-2*n,dHeight:i.height-2*n}:{sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};const s=Math.max(r.dWidth,r.dHeight);if(this.canvasSizeLimit&&s>this.canvasSizeLimit){const t=this.canvasSizeLimit/s;r.dWidth>r.dHeight?(r.dWidth=this.canvasSizeLimit,r.dHeight=Math.round(r.dHeight*t)):(r.dWidth=Math.round(r.dWidth*t),r.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:r,pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?fi.GREY:fi.RGBA,isEnableMirroring:this._isEnableMirroring});if(!o)return null;let a;a=o.pixelFormat===fi.GREY?o.width:4*o.width;let h=!0;return 0===r.sx&&0===r.sy&&r.sWidth===e.width&&r.sHeight===e.height&&(h=!1),{bytes:o.data,width:o.width,height:o.height,stride:a,format:Ss.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_VIDEO_FRAME,isCropped:h,cropRegion:{left:r.sx,top:r.sy,right:r.sx+r.sWidth,bottom:r.sy+r.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:ti(this,os,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,ti(this,cs,"f")&&(ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),ei(this,us,setTimeout(()=>{this.disposed||ti(this,$r,"m",ys).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){ei(this,ls,t,"f")}getPixelFormat(){return ti(this,ls,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(ti(this,$r,"m",ps).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",()=>{t&&this.open(),e.remove()},{once:!0})}),e.addEventListener("change",async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=Xi.convert(ti(this,hs,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=ti(this,ss,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=ti(this,$r,"m",ws).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=ti(this,$r,"m",ws).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!ti(this,hs,"f"))return JSON.parse(JSON.stringify(t));if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});ei(this,ns,t||ti(this,ns,"f"),"f")}let e,i,n=ti(this,hs,"f").left||ti(this,hs,"f").x||0,r=ti(this,hs,"f").top||ti(this,hs,"f").y||0;if(!ti(this,hs,"f").isMeasuredInPercentage)return{x:t.x-(n+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").x),y:t.y-(r+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").y)};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ti(this,$r,"m",ps).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ti(this,$r,"m",ps).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(ti(this,$r,"m",ps).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else e=ti(this,ns,"f").width,i=ti(this,ns,"f").height;return{x:t.x-(Math.round(n*e/100)+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").x),y:t.y-(Math.round(r*i/100)+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").y)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),ei(this,ms,!0,"f")}}var Rs,As,Ds,Ls,Ms,Fs,Ps,ks;Qr=Os,es=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,$r=new WeakSet,ps=function(){return"disabled"!==this.singleFrameMode},_s=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},vs=function(){for(let t in ti(this,ds,"f"))if(1==ti(this,ds,"f")[t])return!0;return!1},ys=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!ti(this,cs,"f"))return ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),void ei(this,us,setTimeout(()=>{this.disposed||ti(this,$r,"m",t).call(this)},this.fetchInterval),"f");const e=()=>{var t;let e;Os._onLog&&Os._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=ti(this,as,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=ti(this,as,"f"))||void 0===t||t.onErrorReceived(mt.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),Os._onLog&&Os._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),ti(this,is,"f").fire("frameAddedToBuffer",null,{async:!1})):Os._onLog&&Os._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case m.BOPM_BLOCK:break;case m.BOPM_UPDATE:e()}else e();ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),ei(this,us,setTimeout(()=>{this.disposed||ti(this,$r,"m",t).call(this)},this.fetchInterval),"f")},ws=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ti(this,$r,"m",ps).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ti(this,$r,"m",ps).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(ti(this,$r,"m",ps).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(ti(this,Ls,"f")||ei(this,Ls,new Ns,"f"),!ti(this,Ls,"f").magnifierCanvas)return;document.body.contains(ti(this,Ls,"f").magnifierCanvas)||(ti(this,Ls,"f").magnifierCanvas.style.position="fixed",ti(this,Ls,"f").magnifierCanvas.style.boxSizing="content-box",ti(this,Ls,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(ti(this,Ls,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void ti(this,Fs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];ti(this,Ls,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(ti(this,Ls,"f").magnifierCanvas.style.left="auto",ti(this,Ls,"f").magnifierCanvas.style.top="0",ti(this,Ls,"f").magnifierCanvas.style.right="0"):(ti(this,Ls,"f").magnifierCanvas.style.left="0",ti(this,Ls,"f").magnifierCanvas.style.top="0",ti(this,Ls,"f").magnifierCanvas.style.right="auto")}ti(this,Ls,"f").show()}),Fs.set(this,()=>{ti(this,Ls,"f")&&ti(this,Ls,"f").hide()}),Ps.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(A(t)){ei(this,Ds,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===_.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Vs){if(!js&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Ws=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ys=(async()=>{})().constructor;let Hs=class extends Ys{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,Ws(t)?e=t:"function"==typeof t&&(e=new Ys(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Ws(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Xs=" is not allowed to change after `createInstance` or `loadWasm` is called.",zs=!js&&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"))||"",qs=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Xs);i._license=e}};!js&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ks=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Ks(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Xs);i._licenseServer=e}},Js=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Xs);i._deviceFriendlyName=e}};let $s,Qs,to,eo,io;"undefined"!=typeof navigator&&($s=navigator,Qs=$s.userAgent,to=$s.platform,eo=$s.mediaDevices),function(){if(!js){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:$s.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:to,search:"Win"},Mac:{str:to},Linux:{str:to}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Qs,o=r.search||e,a=r.verStr||Qs,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Qs,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Qs.indexOf("Windows NT")&&(r="HarmonyOS"),io={browser:i,version:n,OS:r}}js&&(io={browser:"ssr",version:0,OS:"ssr"})}(),eo&&eo.getUserMedia,"Chrome"===io.browser&&io.version>66||"Safari"===io.browser&&io.version>13||"OPR"===io.browser&&io.version>43||"Edge"===io.browser&&io.version;const no=()=>(Yt.loadWasm(),Dt("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=so;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Ks(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Us.crypto||(s="Please upgrade your browser to support online key."),Us.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Xs)})(),o=new Hs;so._pLoad.task=o,(async()=>{try{await so._pLoad}catch(t){}})();let a=Ft();Pt[a]=e=>{if(e.message&&so._onAuthMessage){let t=so._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(kt&&kt("init license success"),e.message&&console.warn(e.message),Yt._bSupportIRTModule=e.bSupportIRTModule,Yt._bSupportDce4Module=e.bSupportDce4Module,so.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=V(Yt.engineResourcePaths),i=("DCV"===Yt._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:so._bNeverShowDialog,engineResourcePath:i,_onLog:kt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await At("core"),Lt.postMessage({type:"license_dynamsoft",body:{v:"4.0.60-dev-20250812170103",brtk:!!t,bptk:1===t,l:e,os:io,fn:so.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),so.bCallInitLicense=!0,await o}));let ro;Vt.license={},Vt.license.dynamsoft=no,Vt.license.getAR=async()=>{{let t=Rt.dynamsoft_inited;t&&t.isRejected&&await t}return Lt?new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){delete i.success;{let t=so.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)}},Lt.postMessage({type:"license_getAR",id:i})}):null};let so=class t{static setLicenseServer(e){Zs(t,e)}static get license(){return this._license}static set license(e){qs(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Zs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Js(t,e)}static initLicense(e,i){if(qs(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return no()}static setDeviceFriendlyName(e){Js(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await Dt("dynamsoft_uuid",async()=>{await Yt.loadWasm();let t=new Hs,e=Ft();Pt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Lt.postMessage({type:"license_getDeviceUUID",id:e}),ro=await t}),ro))()}};so._pLoad=new Hs,so.bPassValidation=!1,so.bCallInitLicense=!1,so._license=zs,so._licenseServer=[],so._deviceFriendlyName="",Yt.engineResourcePaths.license={version:"4.0.60-dev-20250812170103",path:Gs,isInternal:!0},Gt.license={wasm:!0,js:!0},Vt.license.LicenseManager=so;const oo="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,oo)<0&&(Yt.engineResourcePaths.std={version:oo,path:(t=>{if(null==t&&(t="./"),js||Vs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Gs+`../../dynamsoft-capture-vision-std@${oo}/dist/`),isInternal:!0});let ao=class{static getVersion(){return`4.0.60-dev-20250812170103(Worker: ${Ut.license&&Ut.license.worker||"Not Loaded"}, Wasm: ${Ut.license&&Ut.license.wasm||"Not Loaded"})`}};const ho=()=>window.matchMedia("(orientation: landscape)").matches,lo=t=>Object.prototype.toString.call(t).slice(8,-1);function co(t,e){for(const i in e)"Object"===lo(e[i])&&i in t?co(t[i],e[i]):t[i]=e[i];return t}function uo(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function fo(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;ie.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const mo="undefined"==typeof self,po="function"==typeof importScripts,_o=(()=>{if(!po){if(!mo&&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"./"}})(),vo=t=>{if(null==t&&(t="./"),mo||po);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Yt.engineResourcePaths.utility={version:"2.0.60-dev-20250812170132",path:_o,isInternal:!0},Gt.utility={js:!0,wasm:!0};const yo="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,yo)<0&&(Yt.engineResourcePaths.std={version:yo,path:vo(_o+`../../dynamsoft-capture-vision-std@${yo}/dist/`),isInternal:!0});const wo="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,wo)<0)&&(Yt.engineResourcePaths.dip={version:wo,path:vo(_o+`../../dynamsoft-image-processing@${wo}/dist/`),isInternal:!0});let Co=class{static getVersion(){return`2.0.60-dev-20250812170132(Worker: ${Ut.utility&&Ut.utility.worker||"Not Loaded"}, Wasm: ${Ut.utility&&Ut.utility.wasm||"Not Loaded"})`}};function Eo(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const So="undefined"==typeof self,bo="function"==typeof importScripts,To=(()=>{if(!bo){if(!So&&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"./"}})(),Io=t=>{if(null==t&&(t="./"),So||bo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Yt.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:To,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const xo="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,xo)<0&&(Yt.engineResourcePaths.std={version:xo,path:Io(To+`../../dynamsoft-capture-vision-std@${xo}/dist/`),isInternal:!0});const Oo="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,Oo)<0)&&(Yt.engineResourcePaths.dip={version:Oo,path:Io(To+`../../dynamsoft-image-processing@${Oo}/dist/`),isInternal:!0});const Ro={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Ao,Do,Lo,Mo,Fo,Po,ko,No,Bo,jo;function Uo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Wo(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Xo(t){let e=0;for(let i=0;i0}function qo(t,e){for(let i=0;i<4;i++)if(!zo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}(Fo=Ao||(Ao={}))[Fo.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",Fo[Fo.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",Fo[Fo.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Do||(Do={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(Lo||(Lo={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(Mo||(Mo={}));function Ko(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Wo(r)[3],h=Wo(r)[1],l=Wo(s)[3],c=Wo(s)[1];let u,d=0;if(u=Math.max(Math.abs(Go(a,e.points[0])),Math.abs(Go(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Go(h,e.points[1])),Math.abs(Go(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Go(l,t.points[0])),Math.abs(Go(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Go(c,t.points[1])),Math.abs(Go(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Yo(Wo(r)[0]),g=Yo(Wo(r)[2]),m=Yo(Wo(s)[0]),p=Yo(Wo(s)[2]),_=Vo(f,p),v=Vo(m,g),y=_>v,w=Math.min(_,v),C=Vo(f,g),E=Vo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(qo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(qo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(qo(t,this.location.points[e]))return!0;if(qo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Go(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Ho(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{Uo(e,t)&&i.push(t)}),e.forEach(e=>{Uo(t,e)&&i.push(e)}),Xo(function(t){if(t.length<=1)return t;t.sort((t,e)=>t.x-e.x||t.y-e.y);const e=t.shift();return t.sort((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x)),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Jo={barcode:2,text_line:4,detected_quad:8,deskewed_image:16},$o=t=>Object.values(Jo).includes(t)||Jo.hasOwnProperty(t),Qo=(t,e)=>"string"==typeof t?e[Jo[t]]:e[t],ta=(t,e,i)=>{"string"==typeof t?e[Jo[t]]=i:e[t]=i},ea=(t,e,i)=>{const n=[{type:ft.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:ft.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class ia{constructor(){this.verificationEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!0,[ft.CRIT_DETECTED_QUAD]:!0,[ft.CRIT_DESKEWED_IMAGE]:!1},this.duplicateFilterEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},this.duplicateForgetTime={[ft.CRIT_BARCODE]:3e3,[ft.CRIT_TEXT_LINE]:3e3,[ft.CRIT_DETECTED_QUAD]:3e3,[ft.CRIT_DESKEWED_IMAGE]:3e3},this.latestOverlappingEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[ft.CRIT_BARCODE]:5,[ft.CRIT_TEXT_LINE]:5,[ft.CRIT_DETECTED_QUAD]:5,[ft.CRIT_DESKEWED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,Po.set(this,new Map),ko.set(this,new Map),No.set(this,new Map),Bo.set(this,new Map),jo.set(this,new Map),Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),ea(this,t,ft.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{ea(this,t,ft.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){Eo(this,Po,"f").forEach((t,e)=>{ta(e,this.verificationEnabled,t)}),Eo(this,ko,"f").forEach((t,e)=>{ta(e,this.duplicateFilterEnabled,t)}),Eo(this,No,"f").forEach((t,e)=>{ta(e,this.duplicateForgetTime,t)}),Eo(this,Bo,"f").forEach((t,e)=>{ta(e,this.latestOverlappingEnabled,t)}),Eo(this,jo,"f").forEach((t,e)=>{ta(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){$o(t)&&Eo(this,Po,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!$o(t)&&Qo(t,this.verificationEnabled)}enableResultDeduplication(t,e){$o(t)&&(e&&this.enableLatestOverlapping(t,!1),Eo(this,ko,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!$o(t)&&Qo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){$o(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Eo(this,No,"f").set(t,e))}getDuplicateForgetTime(t){return $o(t)?Qo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){$o(t)&&Eo(this,jo,"f").set(t,e)}getMaxOverlappingFrames(t){return $o(t)?Qo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){$o(t)&&(e&&this.enableResultDeduplication(t,!1),Eo(this,Bo,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!$o(t)&&Qo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[ft.CRIT_BARCODE,ft.CRIT_TEXT_LINE,ft.CRIT_DETECTED_QUAD,ft.CRIT_DESKEWED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ro.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ro.BF_GS1_DATABAR))!=BigInt(0);return new Zo(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ro.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ro.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}f.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),d.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}Po=new WeakMap,ko=new WeakMap,No=new WeakMap,Bo=new WeakMap,jo=new WeakMap;const na=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:_.IPF_ABGR_8888}};var ra,sa,oa,aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ca,Ea,Sa,ba,Ta,Ia,xa,Oa,Ra,Aa,Da,La,Ma;class Fa{async readFromFile(t){return await na(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=X(t);return G(n,e,i)}async readFromMemory(t){if(!Eo(Fa,ra,"f",sa).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=Eo(Fa,ra,"f",sa).get(t);return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{var i,n;if(e.success)return function(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");r?r.value=i:e.set(t,i)}(i=Fa,ra,(n=Eo(i,ra,"f",oa),++n),0,oa),Eo(Fa,ra,"f",sa).set(Eo(Fa,ra,"f",oa),JSON.parse(e.memery)),t(Eo(Fa,ra,"f",oa));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}ra=Fa,sa={value:new Map},oa={value:0};class Pa{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await na(t);else if("string"==typeof t){let e=await B(t,"blob");a=await na(e)}else A(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return o&&(new Fa).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}}class ka{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await na(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await na(t);return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await na(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}}!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(aa||(aa={}));class Na{constructor(t){if(ha.add(this),ua.set(this,void 0),da.set(this,{status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]}),fa.set(this,!1),ga.set(this,void 0),ma.set(this,void 0),pa.set(this,void 0),_a.set(this,void 0),this.config=fo(Ht),t&&"object"!=typeof t||Array.isArray(t))throw"Invalid config.";co(this.config,t),Os._isRTU=!0}get disposed(){return e(this,fa,"f")}launch(){return t(this,void 0,void 0,function*(){if(e(this,fa,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(e(Na,la,"f",ca)&&!e(Na,la,"f",ca).isFulfilled&&!e(Na,la,"f",ca).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return i(Na,la,new qt,"f",ca),yield e(this,ha,"m",va).call(this),e(Na,la,"f",ca)})}decode(n,r="ReadBarcodes_Default"){return t(this,void 0,void 0,function*(){i(this,ma,r,"f"),yield e(this,ha,"m",ya).call(this,!0),e(this,_a,"f")||i(this,_a,new ia,"f"),e(this,_a,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(e(this,_a,"f"));const t=new Ge;t.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(t);const s=yield this._cvRouter.capture(n,r);return e(this,_a,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(e(this,_a,"f")),this._cvRouter.removeResultReceiver(t),s})}dispose(){var t,n,r,s,o,a,h;i(this,fa,!0,"f"),e(Na,la,"f",ca)&&e(Na,la,"f",ca).isPending&&e(Na,la,"f",ca).resolve(e(this,da,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(n=this._cameraView)||void 0===n||n.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",e(this,ua,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}la=Na,ua=new WeakMap,da=new WeakMap,fa=new WeakMap,ga=new WeakMap,ma=new WeakMap,pa=new WeakMap,_a=new WeakMap,ha=new WeakSet,va=function(){return t(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield e(this,ha,"m",ya).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),uo(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){e(this,ha,"m",Aa).call(this),e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,ma,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(t){e(this,da,"f").status={code:l.RS_FAILED,message:t.message||t},e(Na,la,"f",ca).reject(new Error(e(this,da,"f").status.message)),this.dispose()}finally{e(this,ha,"m",La).call(this,"Loading...",!1)}})},ya=function(n=!1){return t(this,void 0,void 0,function*(){if(Yt.engineResourcePaths=this.config.engineResourcePaths,!n){const t=V(Yt.engineResourcePaths);if(this._cameraView=yield Pr.createInstance(t.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this.config.scanMode===a.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),this._cameraEnhancer=yield Os.createInstance(this._cameraView),this.disposed)return;if(yield e(this,ha,"m",Ca).call(this),this.disposed)return;if(this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1),i(this,pa,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}}yield so.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield Ve.createInstance()),this.disposed||(this.config.scanMode!==a.SM_SINGLE||n?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{e(Na,la,"f",ca).reject(new Error(t.message)),this.dispose()},yield e(this,ha,"m",wa).call(this,n),this.disposed||n||(this._cvRouter.setInput(this._cameraEnhancer),e(this,ha,"m",Ea).call(this),yield e(this,ha,"m",Sa).call(this),this.disposed)))})},wa=function(n=!1){return t(this,void 0,void 0,function*(){if(n||(this.config.scanMode===a.SM_SINGLE?i(this,ma,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===a.SM_MULTI_UNIQUE&&i(this,ma,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const t=yield this._cvRouter.getSimplifiedSettings(e(this,ma,"f"));if(this.disposed)return;n||this.config.scanMode!==a.SM_SINGLE||(t.outputOriginalImage=!0);let r=this.config.barcodeFormats;if(r){Array.isArray(r)||(r=[r]),t.barcodeSettings.barcodeFormatIds=BigInt(0);for(let e=0;e{document.head.appendChild(t.cloneNode(!0))}),i(this,ga,v.querySelector(".result-item"),"f");const w=v.querySelector(".btn-clear");if(w&&(w.addEventListener("click",()=>{e(this,da,"f").barcodeResults=[],e(this,ha,"m",Oa).call(this)}),null===(s=null===(r=null===(n=this.config)||void 0===n?void 0:n.resultViewConfig)||void 0===r?void 0:r.toolbarButtonsConfig)||void 0===s?void 0:s.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;w.style.display=t.isHidden?"none":"flex",w.className=t.className?t.className:"btn-clear",w.innerText=t.label?t.label:"Clear",t.isHidden&&(v.querySelector(".toolbar-btns").style.justifyContent="center")}const C=v.querySelector(".btn-done");if(C&&(C.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(u=null===(c=null===(h=this.config)||void 0===h?void 0:h.resultViewConfig)||void 0===c?void 0:c.toolbarButtonsConfig)||void 0===u?void 0:u.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;C.style.display=t.isHidden?"none":"flex",C.className=t.className?t.className:"btn-done",C.innerText=t.label?t.label:"Done",t.isHidden&&(v.querySelector(".toolbar-btns").style.justifyContent="center")}if(null===(f=null===(d=this.config)||void 0===d?void 0:d.scannerViewConfig)||void 0===f?void 0:f.showCloseButton){const t=v.querySelector(".btn-close");t&&(t.style.display="",t.addEventListener("click",()=>{e(this,da,"f").barcodeResults=[],e(this,da,"f").status={code:l.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}if(null===(g=this.config)||void 0===g?void 0:g.scannerViewConfig.showFlashButton){const i=v.querySelector(".btn-flash-auto"),n=v.querySelector(".btn-flash-open"),r=v.querySelector(".btn-flash-close");if(i){i.style.display="";let s=null,o=250,a=20,h=3;const l=(l=250)=>t(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==s){if(!(lt(this,void 0,void 0,function*(){var t;if(e(this,fa,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(s),void(s=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(s),s=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(_.IPF_GRAYSCALED===l.format){for(let t=0;t=h){null===(t=Os._onLog)||void 0===t||t.call(Os,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,i.style.display="none",n.style.display="",r.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});s=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),i.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),i.style.display="none",n.style.display="",r.style.display="none"})),n.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),i.style.display="none",n.style.display="none",r.style.display=""})),r.addEventListener("click",()=>t(this,void 0,void 0,function*(){l(1e3),i.style.display="",n.style.display="none",r.style.display="none"}))}}let E=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(E)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const i=v.querySelector(".camera-control");if(i){i.style.display="";const n=yield this._cameraEnhancer.getAllCameras(),r=this.config.scannerViewConfig.cameraSwitchControl,s=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px"}),e},o=()=>{if(0===n.length)return null;if("listAll"===r){const i=v.querySelector(".camera-list");for(let t of n){const e=s(t);i.append(e)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const r=t=>{for(let e of o)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};i.addEventListener("click",i=>t(this,void 0,void 0,function*(){const t=i.target;e(this,ha,"m",La).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:t.deviceId,label:t.label,_checked:t._checked});const n=this._cameraEnhancer.getSelectedCamera(),s=this._cameraEnhancer.getCapabilities();uo(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(s.torch?e(this,ha,"m",Da).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),r(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,ma,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),e(this,ha,"m",La).call(this,"Loading...",!1)}));const o=v.querySelectorAll(".camera-list div");return()=>t(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();r(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===r?()=>t(this,void 0,void 0,function*(){e(this,ha,"m",La).call(this,"Accessing Camera...",!0);const t=uo(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&e(this,ha,"m",Da).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),e(this,ha,"m",La).call(this,"Loading...",!1)}):void 0},a=o();i.addEventListener("click",e=>t(this,void 0,void 0,function*(){e.stopPropagation(),a&&(yield a())}))}}this.config.showUploadImageButton&&e(this,ha,"m",Aa).call(this,v.querySelector(".btn-upload-image"));const S=this._cameraView.getUIElement();S.shadowRoot.querySelector(".dce-sel-camera").remove(),S.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const b=v.querySelector(".barcode-scanner-container");b.style.display=ho()?"flex":"",this.config.scanMode===a.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===a.SM_SINGLE&&(this.config.showResultView=!1);const T=this.config.showResultView;let I;if(this.config.container?(b.style.position="relative",I=this.config.container):I=document.body,"string"==typeof I&&(I=document.querySelector(I),null===I))throw new Error("Failed to get the container");let x=this.config.scannerViewConfig.container;if("string"==typeof x&&(x=document.querySelector(x),null===x))throw new Error("Failed to get the container of the scanner view.");let O=this.config.resultViewConfig.container;if("string"==typeof O&&(O=document.querySelector(O),null===O))throw new Error("Failed to get the container of the result view.");const R=v.querySelector(".scanner-view-container"),A=v.querySelector(".result-view-container"),D=v.querySelector(".loading-page");R.append(D),x&&(R.append(S),x.append(R)),O&&O.append(A),x||O?x&&!O?(this.config.container||(A.style.position="absolute"),O=A,I.append(A)):!x&&O&&(this.config.container||(R.style.position="absolute"),x=R,R.append(S),I.append(R)):(x=R,O=A,T&&(Object.assign(R.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"}),Object.assign(A.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"})),R.append(S),I.append(b)),document.querySelector(".result-view-container").style.display=T?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),i(this,ua,()=>{Object.assign(b.style,{display:ho()?"flex":""}),!T||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(x.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"}),Object.assign(O.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"}))},"f"),window.addEventListener("resize",e(this,ua,"f")),this._cameraView._createDrawingLayer(2)})},Ea=function(){const i=new Ge;i.onCapturedResultReceived=i=>t(this,void 0,void 0,function*(){if(e(this,pa,"f")&&e(this,pa,"f").clearDrawingItems(),i.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of i.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));e(this,pa,"f").addDrawingItems(t)}this.config.scanMode===a.SM_SINGLE?e(this,ha,"m",ba).call(this,i):e(this,ha,"m",Ta).call(this,i)}}),this._cvRouter.addResultReceiver(i)},Sa=function(){return t(this,void 0,void 0,function*(){e(this,_a,"f")||i(this,_a,new ia,"f"),e(this,_a,"f").enableResultCrossVerification(2,!0),e(this,_a,"f").enableResultDeduplication(2,!0),e(this,_a,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(e(this,_a,"f")),e(this,_a,"f").isResultCrossVerificationEnabled=()=>!1,e(this,_a,"f").isResultDeduplicationEnabled=()=>!1})},ba=function(t){const i=this._cameraView.getUIElement().shadowRoot;let n=new Promise(n=>{if(t.decodedBarcodesResult.barcodeResultItems.length>1){e(this,ha,"m",xa).call(this);for(let e of t.decodedBarcodesResult.barcodeResultItems){let t=0,r=0;for(let i=0;i<4;++i){let n=e.location.points[i];t+=n.x,r+=n.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:t/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{n(e)}),i.append(o)}}else n(t.decodedBarcodesResult.barcodeResultItems[0])});n.then(i=>{const n=t.items.filter(t=>t.type===ft.CRIT_ORIGINAL_IMAGE)[0].imageData,r={status:{code:l.RS_SUCCESS,message:"Success."},originalImageResult:n,barcodeImage:(()=>{const t=W(n),e=i.location.points,r=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-r,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-r,e[0].y-s);for(let t=1;t`${t.formatString}_${t.text}`==`${i.formatString}_${i.text}`);-1===t?(i.count=1,e(this,da,"f").barcodeResults.unshift(i),e(this,ha,"m",Oa).call(this,i)):(e(this,da,"f").barcodeResults[t].count++,e(this,ha,"m",Ra).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},Ia=function(t){const i=e(this,ga,"f").cloneNode(!0);i.querySelector(".format-string").innerText=t.formatString;i.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),i.id=`${t.formatString}_${t.text}`;return i.querySelector(".delete-icon").addEventListener("click",()=>{const i=[...document.querySelectorAll(".main-list .result-item")],n=i.findIndex(e=>e.id===`${t.formatString}_${t.text}`);e(this,da,"f").barcodeResults.splice(n,1),i[n].remove(),0===e(this,da,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),i},xa=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Oa=function(t){if(!this.config.showResultView)return;const i=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==a.SM_SINGLE))return;const n=document.querySelector(".main-list");if(!t)return n.textContent="",void(this.config.showPoweredByDynamsoft&&(i.style.display=""));i.style.display="none";const r=e(this,ha,"m",Ia).call(this,t);n.insertBefore(r,document.querySelector(".result-item"))},Ra=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},Aa=function(i){i||(i=document.querySelector(".btn-upload-image")),i&&(i.style.display="",i.onchange=i=>t(this,void 0,void 0,function*(){const t=i.target.files,n={status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]};let r=0;e(this,ha,"m",La).call(this,`Capturing... [${r}/${t.length}]`,!0);let s=!1;for(let e=0;e`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===i?(t.count=1,e(this,da,"f").barcodeResults.unshift(t),e(this,ha,"m",Oa).call(this,t)):(e(this,da,"f").barcodeResults[i].count++,e(this,ha,"m",Ra).call(this,i))}else if(s.decodedBarcodesResult.barcodeResultItems)for(let t of s.decodedBarcodesResult.barcodeResultItems){const e=n.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,n.barcodeResults.push(t))}e(this,ha,"m",La).call(this,`Capturing... [${++r}/${t.length}]`,!0)}catch(t){n.status={code:l.RS_FAILED,message:t.message||t},e(Na,la,"f",ca).reject(new Error(n.status.message)),this.dispose()}e(this,ha,"m",La).call(this,"Loading...",!1),this.config.scanMode===a.SM_SINGLE&&(e(Na,la,"f",ca).resolve(n),this.dispose()),i.target.value=""}))},Da=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},La=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},Ma=function(t){let e=Ft();Pt[e]=()=>{},Lt.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},ca={value:null};const Ba="undefined"==typeof self,ja="function"==typeof importScripts,Ua=(()=>{if(!ja){if(!Ba&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Va=t=>{if(null==t&&(t="./"),Ba||ja);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Yt.engineResourcePaths.dbr={version:"11.0.60-dev-20250812165905",path:Ua,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const Ga="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,Ga)<0&&(Yt.engineResourcePaths.std={version:Ga,path:Va(Ua+`../../dynamsoft-capture-vision-std@${Ga}/dist/`),isInternal:!0});const Wa="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,Wa)<0)&&(Yt.engineResourcePaths.dip={version:Wa,path:Va(Ua+`../../dynamsoft-image-processing@${Wa}/dist/`),isInternal:!0});let Ya=class{static getVersion(){const t=Ut.dbr&&Ut.dbr.wasm;return`11.0.60-dev-20250812165905(Worker: ${Ut.dbr&&Ut.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const Ha={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Xa,za,qa,Ka,Za,Ja;function $a(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Qa(e,t,"map"),t.getFieldRawValue=t=>Qa(e,t,"raw"),t.getFieldMappingStatus=t=>th(e,t),t.getFieldValidationStatus=t=>eh(e,t),delete t.fullCodeString}function Qa(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=Qa(r,e,i);if(void 0!==t)return t}}}function th(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Za[i.MappingStatus]):Za.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=th(n,e);if(void 0!==t)return t}}}function eh(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(Ja[i.ValidationStatus]):Ja.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=eh(n,e);if(void 0!==t)return t}}}function ih(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!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"}(Xa||(Xa={})),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"}(za||(za={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(qa||(qa={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(Ka||(Ka={})),function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(Za||(Za={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(Ja||(Ja={}));const nh=t=>t&&"object"==typeof t&&"function"==typeof t.then,rh=(async()=>{})().constructor;class sh extends rh{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,nh(t)?e=t:"function"==typeof t&&(e=new rh(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(nh(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class oh{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!Vt.license)throw Error("Module `license` is not existed.");await Vt.license.dynamsoft(),await Yt.loadWasm();const t=new oh,e=new sh;let i=Ft();return Pt[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},Lt.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){ih(this);let t=Ft();this.bDestroyed=!0,Pt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Lt.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(ih(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await B(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return ih(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(ih(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise((i,n)=>{let r=Ft();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):($a(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Lt.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const ah="undefined"==typeof self,hh="function"==typeof importScripts,lh=(()=>{if(!hh){if(!ah&&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"./"}})();Yt.engineResourcePaths.dcp={version:"3.0.60-dev-20250812165958",path:lh,isInternal:!0},Gt.dcp={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE]},Vt.dcp={handleParsedResultItem:$a};const ch="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,ch)<0&&(Yt.engineResourcePaths.std={version:ch,path:(t=>{if(null==t&&(t="./"),ah||hh);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(lh+`../../dynamsoft-capture-vision-std@${ch}/dist/`),isInternal:!0});class uh{static getVersion(){const t=Ut.dcp&&Ut.dcp.wasm;return`3.0.60-dev-20250812165958(Worker: ${Ut.dcp&&Ut.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await Yt.loadWasm(),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],o=V(Yt.engineResourcePaths);Lt.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===Yt._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}}Yt._bundleEnv="DBR",Ve._defaultTemplate="ReadSingleBarcode",Yt.engineResourcePaths.rootDirectory=o(s+"../../"),Yt.engineResourcePaths.dbrBundle={version:"11.0.6000",path:s,isInternal:!0};export{Ya as BarcodeReaderModule,Na as BarcodeScanner,Os as CameraEnhancer,Qe as CameraEnhancerModule,Br as CameraManager,Pr as CameraView,Ve as CaptureVisionRouter,de as CaptureVisionRouterModule,Ge as CapturedResultReceiver,oh as CodeParser,uh as CodeParserModule,Yt as CoreModule,Oi as DrawingItem,Rr as DrawingStyleManager,Ha as EnumBarcodeFormat,m as EnumBufferOverflowProtectionMode,ft as EnumCapturedResultItemType,p as EnumColourChannelUsageType,gt as EnumCornerType,Ct as EnumCrossVerificationStatus,Ka as EnumDeblurMode,ci as EnumDrawingItemMediaType,ui as EnumDrawingItemState,di as EnumEnhancedFeatures,mt as EnumErrorCode,Xa as EnumExtendedBarcodeResultType,aa as EnumFilterType,pt as EnumGrayscaleEnhancementMode,_t as EnumGrayscaleTransformationMode,It as EnumImageCaptureDistanceMode,Tt as EnumImageFileFormat,_ as EnumImagePixelFormat,fe as EnumImageSourceState,vt as EnumImageTagType,Et as EnumIntermediateResultUnitType,qa as EnumLocalizationMode,Za as EnumMappingStatus,xt as EnumModuleName,h as EnumOptimizationMode,yt as EnumPDFReadingMode,Ye as EnumPresetTemplate,za as EnumQRCodeErrorCorrectionLevel,wt as EnumRasterDataSource,St as EnumRegionObjectElementType,l as EnumResultStatus,a as EnumScanMode,bt as EnumSectionType,Ot as EnumTransformMatrixType,Ja as EnumValidationStatus,Es as Feedback,Gi as GroupDrawingItem,kr as ImageDataGetter,Pa as ImageDrawer,Pi as ImageDrawingItem,Bs as ImageEditorView,Fa as ImageIO,ka as ImageProcessor,ht as ImageSourceAdapter,We as IntermediateResultReceiver,so as LicenseManager,ao as LicenseModule,Ui as LineDrawingItem,ia as MultiFrameResultCrossFilter,Vi as QuadDrawingItem,Ri as RectDrawingItem,Ni as TextDrawingItem,Co as UtilityModule,X as _getNorImageData,G as _saveToFile,H as _toBlob,W as _toCanvas,Y as _toImage,Bt as bDebug,j as checkIsLink,U as compareVersion,Dt as doOrWaitAsyncDependency,Ft as getNextTaskID,V as handleEngineResourcePaths,Ut as innerVersions,I as isArc,x as isContour,A as isDSImageData,D as isDSRect,L as isImageTag,M as isLineSegment,T as isObject,R as isOriginalDsImageData,F as isPoint,P as isPolygon,k as isQuad,N as isRect,z as isSimdSupported,Rt as mapAsyncDependency,Vt as mapPackageRegister,Pt as mapTaskCallBack,kt as onLog,q as productNameMap,B as requestResource,jt as setBDebug,Nt as setOnLog,At as waitAsyncDependency,Lt as worker,Gt as workerAutoResources}; +function t(t,e,i,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function e(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function i(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const n="undefined"==typeof self,r="function"==typeof importScripts,s=(()=>{if(!r){if(!n&&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"./"}})(),o=t=>{if(null==t&&(t="./"),n||r);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var a,h,l;!function(t){t[t.SM_SINGLE=0]="SM_SINGLE",t[t.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(a||(a={})),function(t){t[t.OM_NONE=0]="OM_NONE",t[t.OM_SPEED=1]="OM_SPEED",t[t.OM_COVERAGE=2]="OM_COVERAGE",t[t.OM_BALANCE=3]="OM_BALANCE",t[t.OM_DPM=4]="OM_DPM",t[t.OM_DENSE=5]="OM_DENSE"}(h||(h={})),function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(l||(l={}));const c=t=>t&&"object"==typeof t&&"function"==typeof t.then,u=(async()=>{})().constructor;let d=class extends u{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,c(t)?e=t:"function"==typeof t&&(e=new u(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(c(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function f(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function g(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var m,p,_;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(m||(m={})),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"}(p||(p={})),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"}(_||(_={}));const v="undefined"==typeof self,y="function"==typeof importScripts,w=(()=>{if(!y){if(!v&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),C=t=>{if(null==t&&(t="./"),v||y);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},E=t=>Object.prototype.toString.call(t),S=t=>Array.isArray?Array.isArray(t):"[object Array]"===E(t),b=t=>"number"==typeof t&&!Number.isNaN(t),T=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),I=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.radius)||t.radius<0||!b(t.startAngle)||!b(t.endAngle)),x=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),O=t=>!(!T(t)||!b(t.width)||t.width<=0||!b(t.height)||t.height<=0||!b(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!L(t.tag)),R=t=>!(!O(t)||!b(t.bytes.length)&&!b(t.bytes.ptr)),A=t=>!!O(t)&&t.bytes instanceof Uint8Array,D=t=>!(!T(t)||!b(t.left)||t.left<0||!b(t.top)||t.top<0||!b(t.right)||t.right<0||!b(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),L=t=>null===t||!!T(t)&&!!b(t.imageId)&&"type"in t,M=t=>!(!T(t)||!F(t.startPoint)||!F(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),F=t=>!!T(t)&&!!b(t.x)&&!!b(t.y),P=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),k=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!F(t)),N=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.width)||t.width<0||!b(t.height)||t.height<0),B=async(t,e,i)=>await new Promise((n,r)=>{let s=new XMLHttpRequest;s.responseType=e,s.onloadstart=()=>{i&&i.loadstartCallback&&i.loadstartCallback()},s.onloadend=async()=>{i&&i.loadendCallback&&i.loadendCallback(),s.status<200||s.status>=300?r(new Error(t+" "+s.status)):n(s.response)},s.onprogress=t=>{i&&i.progressCallback&&i.progressCallback(t)},s.onerror=()=>{r(new Error("Network Error: "+s.statusText))},s.open("GET",t,!0),s.send()}),j=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),U=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${q[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${q[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},G=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await H(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),W=t=>{A(t)&&(t=X(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},Y=(t,e)=>{A(e)&&(e=X(e));const i=W(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},H=async(t,e)=>{A(e)&&(e=X(e));const i=W(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},X=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===_.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===_.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},z=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),q={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var K,Z,J,$,Q,tt,et,it;let nt,rt,st,ot,at,ht=class t{get _isFetchingStarted(){return f(this,Q,"f")}constructor(){K.add(this),Z.set(this,[]),J.set(this,1),$.set(this,m.BOPM_BLOCK),Q.set(this,!1),tt.set(this,void 0),et.set(this,p.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!A(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(f(this,Z,"f").length>=f(this,J,"f"))switch(f(this,$,"f")){case m.BOPM_BLOCK:break;case m.BOPM_UPDATE:if(f(this,Z,"f").push(t),T(f(this,tt,"f"))&&b(f(this,tt,"f").imageId)&&1==f(this,tt,"f").keepInBuffer)for(;f(this,Z,"f").length>f(this,J,"f");){const t=f(this,Z,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==f(this,tt,"f").imageId});f(this,Z,"f").splice(t,1)}else f(this,Z,"f").splice(0,f(this,Z,"f").length-f(this,J,"f"))}else f(this,Z,"f").push(t)}getImage(){if(0===f(this,Z,"f").length)return null;let e;if(f(this,tt,"f")&&b(f(this,tt,"f").imageId)){const t=f(this,K,"m",it).call(this,f(this,tt,"f").imageId);if(t<0)throw new Error(`Image with id ${f(this,tt,"f").imageId} doesn't exist.`);e=f(this,Z,"f").slice(t,t+1)[0]}else e=f(this,Z,"f").pop();if([_.IPF_RGB_565,_.IPF_RGB_555,_.IPF_RGB_888,_.IPF_ARGB_8888,_.IPF_RGB_161616,_.IPF_ARGB_16161616,_.IPF_ABGR_8888,_.IPF_ABGR_16161616,_.IPF_BGR_888].includes(e.format)){if(f(this,et,"f")===p.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every(t=>b(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==E(e))throw new TypeError("Invalid 'keepInBuffer'.");g(this,tt,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){g(this,tt,null,"f")}hasImage(t){return f(this,K,"m",it).call(this,t)>=0}startFetching(){g(this,Q,!0,"f")}stopFetching(){g(this,Q,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(g(this,J,t,"f");f(this,Z,"f")&&f(this,Z,"f").length>t;)f(this,Z,"f").shift()}getMaxImageCount(){return f(this,J,"f")}getImageCount(){return f(this,Z,"f").length}clearBuffer(){f(this,Z,"f").length=0}isBufferEmpty(){return 0===f(this,Z,"f").length}setBufferOverflowProtectionMode(t){g(this,$,t,"f")}getBufferOverflowProtectionMode(){return f(this,$,"f")}setColourChannelUsageType(t){g(this,et,t,"f")}getColourChannelUsageType(){return f(this,et,"f")}};Z=new WeakMap,J=new WeakMap,$=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,K=new WeakSet,it=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return f(this,Z,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(nt=navigator,rt=nt.userAgent,st=nt.platform,ot=nt.mediaDevices),function(){if(!v){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:nt.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:st,search:"Win"},Mac:{str:st},Linux:{str:st}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||rt,o=r.search||e,a=r.verStr||rt,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||rt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=rt.indexOf("Windows NT")&&(r="HarmonyOS"),at={browser:i,version:n,OS:r}}v&&(at={browser:"ssr",version:0,OS:"ssr"})}();const lt="undefined"!=typeof WebAssembly&&rt&&!(/Safari/.test(rt)&&!/Chrome/.test(rt)&&/\(.+\s11_2_([2-6]).*\)/.test(rt)),ct=!("undefined"==typeof Worker),ut=!(!ot||!ot.getUserMedia),dt=async()=>{let t=!1;if(ut)try{(await ot.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var ft,gt,mt,pt,_t,vt,yt,wt,Ct;"Chrome"===at.browser&&at.version>66||"Safari"===at.browser&&at.version>13||"OPR"===at.browser&&at.version>43||"Edge"===at.browser&&at.version,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(ft||(ft={})),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"}(gt||(gt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(mt||(mt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV",t[t.GEM_END=-1]="GEM_END"}(pt||(pt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV",t[t.GTM_END=-1]="GTM_END"}(_t||(_t={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(vt||(vt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(yt||(yt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(wt||(wt={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(Ct||(Ct={}));const Et={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var St,bt,Tt,It,xt,Ot;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(St||(St={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(bt||(bt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(Tt||(Tt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(It||(It={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(xt||(xt={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(Ot||(Ot={}));const Rt={},At=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Rt[t]=Rt[t]||new d);await Promise.all(i)},Dt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=Rt[t]=Rt[t]||new d(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let Lt,Mt=0;const Ft=()=>Mt++,Pt={};let kt;const Nt=t=>{kt=t,Lt&&Lt.postMessage({type:"setBLog",body:{value:!!t}})};let Bt=!1;const jt=t=>{Bt=t,Lt&&Lt.postMessage({type:"setBDebug",body:{value:!!t}})},Ut={},Vt={},Gt={dip:{wasm:!0}},Wt={std:{version:"2.0.0",path:C(w+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.2.20-dev-20251029130528",path:w,isInternal:!0}};let Yt=5;"undefined"!=typeof navigator&&(Yt=navigator.hardwareConcurrency?navigator.hardwareConcurrency-1:5),Pt[-3]=async t=>{Ht.onWasmLoadProgressChanged&&Ht.onWasmLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class Ht{static get engineResourcePaths(){return Wt}static set engineResourcePaths(t){Object.assign(Wt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return kt}static set _onLog(t){Nt(t)}static get _bDebug(){return Bt}static set _bDebug(t){jt(t)}static get _workerName(){return`${Ht._bundleEnv.toLowerCase()}.bundle.worker.js`}static get wasmLoadOptions(){return Ht._wasmLoadOptions}static set wasmLoadOptions(t){Object.assign(Ht._wasmLoadOptions,t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Rt[t]&&Rt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=Rt.core;e=!i||i.isEmpty,e||await At("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),xt.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||xt.MN_DYNAMSOFT_CORE==t)return;let e=Gt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=Rt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await Dt(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await At(o);const i=V(Wt),r={};for(let e of t)r[e]=Gt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:Ht._bundleEnv,wasmLoadOptions:Ht.wasmLoadOptions};let a=new d;if(e){s.needLoadCore=!0;let t=i[`${Ht._bundleEnv.toLowerCase()}Bundle`]+Ht._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),Lt=new Worker(t),Lt.onerror=t=>{let e=new Error(t.message);a.reject(e)},Lt.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":kt&&kt(e.message);break;case"warning":console.warn(e.message);break;case"task":try{Pt[n](r),delete Pt[n]}catch(t){throw delete Pt[n],t}break;case"event":try{Pt[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!kt,s.bd=Bt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await At("core");let h=Mt++;Pt[h]=t=>{if(t.success)Object.assign(Ut,t.versions),"{}"!==JSON.stringify(t.versions)&&(Ht._versions=t.versions),Ht.loadedWasmType=t.loadedWasmType,a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},Lt.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:lt,worker:ct,getUserMedia:ut,camera:await dt(),browser:at.browser,version:at.version,OS:at.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.2.20-dev-20251029130528(Worker: ${Ut.core&&Ut.core.worker||"Not Loaded"}, Wasm: ${Ut.core&&Ut.core.wasm||"Not Loaded"})`}static enableLogging(){ht._onLog=console.log,Ht._onLog=console.log}static disableLogging(){ht._onLog=null,Ht._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cfd",id:n,body:{count:t}})})}}Ht._bSupportDce4Module=-1,Ht._bSupportIRTModule=-1,Ht._versions=null,Ht._bundleEnv="DCV",Ht._wasmLoadOptions={wasmType:"auto",pthreadPoolSize:Yt},Ht.loadedWasmType="ml-simd-pthread",Ht.browserInfo=at;var Xt={license:"",scanMode:a.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:Ht.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:s,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const zt=t=>t&&"object"==typeof t&&"function"==typeof t.then,qt=(async()=>{})().constructor;class Kt extends qt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,zt(t)?e=t:"function"==typeof t&&(e=new qt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(zt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Zt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Jt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const $t=t=>t&&"object"==typeof t&&"function"==typeof t.then,Qt=(async()=>{})().constructor;let te=class extends Qt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,$t(t)?e=t:"function"==typeof t&&(e=new Qt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&($t(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},ee=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var ie={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1};const ne=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};let re=class{constructor(t){this._irrRegistryState=ie,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ne(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach((t,e)=>{i[e]=t}),t._observedTaskMap.clear()}return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ne(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const se="undefined"==typeof self,oe="function"==typeof importScripts,ae=(()=>{if(!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"./"}})(),he=t=>{if(null==t&&(t="./"),se||oe);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var le;Ht.engineResourcePaths.cvr={version:"3.2.20-dev-20251030140710",path:ae,isInternal:!0},Gt.cvr={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING,xt.MN_DYNAMSOFT_NEURAL_NETWORK]},Gt.dnn={wasm:!0,deps:[xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.cvr={};const ce="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,ce)<0&&(Ht.engineResourcePaths.std={version:ce,path:he(ae+`../../dynamsoft-capture-vision-std@${ce}/dist/`),isInternal:!0});const ue="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,ue)<0)&&(Ht.engineResourcePaths.dip={version:ue,path:he(ae+`../../dynamsoft-image-processing@${ue}/dist/`),isInternal:!0});const de="2.0.10";(!Ht.engineResourcePaths.dnn||"string"!=typeof Ht.engineResourcePaths.dnn&&U(Ht.engineResourcePaths.dnn.version,de)<0)&&(Ht.engineResourcePaths.dnn={version:de,path:he(ae+`../../dynamsoft-capture-vision-dnn@${de}/dist/`),isInternal:!0});let fe=class{static getVersion(){return this._version}};var ge,me,pe,_e,ve,ye,we,Ce,Ee,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le,Me,Fe,Pe,ke,Ne;function Be(t,e){if(t){if(t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}if(t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}Be(t.referencedItem,e)}}function je(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function Ue(t){return{type:ft.CRIT_ORIGINAL_IMAGE,referenceItem:null,targetROIDefName:"",taskName:"",imageData:t,toCanvas:()=>W(t),toImage:e=>Y(e,t),toBlob:e=>H(e,t)}}function Ve(t){let e=!1;const i=[mt.EC_UNSUPPORTED_JSON_KEY_WARNING,mt.EC_LICENSE_AUTH_QUOTA_EXCEEDED,mt.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}fe._version=`3.2.20-dev-20251030140710(Worker: ${null===(le=Ut.cvr)||void 0===le?void 0:le.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ge||(ge={}));const Ge={onTaskResultsReceived:()=>{},isFilter:!0};Pt[-2]=async t=>{We.onDataLoadProgressChanged&&We.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let We=class t{constructor(){me.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(Ht.browserInfo.OS)?2048:4096,this.onCaptureError=null,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._dynamsoft=!0,pe.set(this,null),_e.set(this,null),ve.set(this,null),ye.set(this,null),we.set(this,null),Ce.set(this,new Set),Ee.set(this,new Set),Se.set(this,new Set),be.set(this,500),Te.set(this,0),Ie.set(this,0),xe.set(this,!1),Oe.set(this,!1),Re.set(this,!1),Ae.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Zt(this,Re,"f")}static async createInstance(e=!0){if(!Vt.license)throw Error("The `license` module cannot be found.");await Vt.license.dynamsoft(),await Ht.loadWasm();const i=new t,n=new te;let r=Ft();return Pt[r]=async e=>{e.success?(i._instanceID=e.instanceID,i._currentSettings=JSON.parse(JSON.parse(e.outputSettings).data),t._isNoOnnx=e.isNoOnnx,fe._version=`3.2.20-dev-20251030140710(Worker: ${Ut.cvr.worker}, Wasm: ${e.version})`,Jt(i,Oe,!0,"f"),Jt(i,ye,i.getIntermediateResultManager(),"f"),Jt(i,Oe,!1,"f"),n.resolve(i)):Ve({message:e.message,rj:n.reject,stack:e.stack,functionName:"createInstance"})},Lt.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendDLModelBuffer(e,i){return await Ht.loadWasm(),t._isNoOnnx?Promise.reject("Model not supported in the current environment."):await new Promise((t,n)=>{let r=Ft();const s=V(Ht.engineResourcePaths);let o;Pt[r]=async e=>{if(e.success){const i=JSON.parse(e.response);return 0!==i.errorCode&&Ve({message:i.errorString?i.errorString:"Append Model Buffer Failed.",rj:n,errorCode:i.errorCode,functionName:"appendDLModelBuffer"}),t(i)}Ve({message:e.message,rj:n,stack:e.stack,functionName:"appendDLModelBuffer"})},i?o=i:"DCV"===Ht._bundleEnv?o=s.dcvData+"models/":"DBR"===Ht._bundleEnv&&(o=s.dbrBundle+"models/"),Lt.postMessage({type:"cvr_appendDLModelBuffer",id:r,body:{modelName:e,path:o}})})}static async clearDLModelBuffers(){return await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();Ve({message:i.message,rj:e,stack:i.stack,functionName:"clearDLModelBuffers"})},Lt.postMessage({type:"cvr_clearDLModelBuffers",id:i})})}async _singleFrameModeCallback(t){for(let e of Zt(this,Ce,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived(Ue(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,Zt(this,pe,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}),Zt(this,me,"m",Me).call(this,i)}setInput(t){if(je(this),!t)return Zt(this,Ae,"f")&&(Zt(this,ye,"f").removeResultReceiver(Zt(this,Ae,"f")),Jt(this,Ae,null,"f")),void Jt(this,pe,null,"f");Jt(this,pe,t,"f"),t.isCameraEnhancer&&Zt(this,ye,"f")&&(Zt(this,pe,"f")._intermediateResultReceiver.isDce=!0,Zt(this,ye,"f").addResultReceiver(Zt(this,pe,"f")._intermediateResultReceiver),Jt(this,Ae,Zt(this,pe,"f")._intermediateResultReceiver,"f"))}getInput(){return Zt(this,pe,"f")}addImageSourceStateListener(t){if(je(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Zt(this,Ee,"f").add(t)}removeImageSourceStateListener(t){return je(this),Zt(this,Ee,"f").delete(t)}addResultReceiver(t){if(je(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Zt(this,Ce,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){je(this),Zt(this,Ce,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Zt(this,Ce,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new te;let i=Ft();return Pt[i]=async t=>{t.success?e.resolve():Ve({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},Lt.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(je(this),!t._dynamsoft)throw new Error("User defined CapturedResultFilter is not supported.");if(!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Zt(this,Se,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){je(this),Zt(this,Se,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Zt(this,ye,"f").removeResultReceiver(Ge),0===Zt(this,Se,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1},e={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1};return await Zt(this,me,"m",Fe).call(this,t),void await Zt(this,me,"m",Pe).call(this,e)}for(let t of Zt(this,Se,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(ft.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(ft.CRIT_BARCODE)&&([...Zt(this,ye,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Zt(this,ye,"f").addResultReceiver(Ge)),await Zt(this,me,"m",Fe).call(this,t.verificationEnabled),await Zt(this,me,"m",Pe).call(this,t.duplicateFilterEnabled),await Zt(this,me,"m",ke).call(this,t.duplicateForgetTime)}async startCapturing(e){if(je(this),!this._isPauseScan)return;if(!Zt(this,pe,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);for(let t of Zt(this,Se,"f"))await this.addResultFilter(t);const i=V(Ht.engineResourcePaths);return void 0!==Zt(this,pe,"f").singleFrameMode&&"disabled"!==Zt(this,pe,"f").singleFrameMode?(this._templateName=e,void Zt(this,pe,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):Zt(this,ve,"f")&&Zt(this,ve,"f").isPending?Zt(this,ve,"f"):(Jt(this,ve,new te((t,n)=>{if(this.disposed)return;let r=Ft();Pt[r]=async i=>{Zt(this,ve,"f")&&!Zt(this,ve,"f").isFulfilled&&(i.success?(this._isPauseScan=!1,this._isOutputOriginalImage=i.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Zt(this,pe,"f").startFetching(),this._loopReadVideo(e),t()},0)):Ve({message:i.message,rj:n,stack:i.stack,functionName:"startCapturing"}))},Lt.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:i}})}),"f"),await Zt(this,ve,"f"))}stopCapturing(){je(this),Zt(this,pe,"f")&&(Zt(this,pe,"f").isCameraEnhancer&&void 0!==Zt(this,pe,"f").singleFrameMode&&"disabled"!==Zt(this,pe,"f").singleFrameMode?Zt(this,pe,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Zt(this,me,"m",Ne).call(this),Zt(this,pe,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Jt(this,ve,null,"f"),Zt(this,pe,"f").setColourChannelUsageType(p.CCUT_AUTO)))}async containsTask(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));Ve({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},Lt.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async switchCapturingTemplate(t){this.stopCapturing(),await this.startCapturing(t)}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Jt(this,xe,!0,"f"),Zt(this,pe,"f").isBufferEmpty())if(Zt(this,pe,"f").hasNextImageToFetch())for(let t of Zt(this,Ee,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ge.ISS_BUFFER_EMPTY);else if(!Zt(this,pe,"f").hasNextImageToFetch())for(let t of Zt(this,Ee,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ge.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Zt(this,pe,"f").isBufferEmpty()&&Zt(this,pe,"f").isCameraEnhancer)try{Zt(this,pe,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Zt(this,pe,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Zt(this,pe,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Zt(this,pe,"f").isCameraEnhancer&&Zt(this,pe,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Zt(this,pe,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Zt(this,Ce,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived(Ue(this._dsImage));const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null,Zt(this,pe,"f").isCameraEnhancer&&Zt(this,pe,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify});for(let t of Zt(this,Se,"f")){const e=t;e.onOriginalImageResultReceived(n),e.onDecodedBarcodesReceived(n),e.onRecognizedTextLinesReceived(n),e.onProcessedDocumentResultReceived(n),e.onParsedResultsReceived(n)}Zt(this,me,"m",Me).call(this,n);const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Zt(this,pe,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Zt(this,pe,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async getClarity(t,e,i,n,r){const{bytes:s,width:o,height:a,stride:h,format:l}=t;let c=Ft();return new Promise((t,u)=>{Pt[c]=async e=>{e.success?t(e.clarity):Ve({message:e.message,rj:u,stack:e.stack,functionName:"getClarity"})},Lt.postMessage({type:"cvr_getClarity",id:c,instanceID:this._instanceID,body:{bytes:s,width:o,height:a,stride:h,format:l,bitcount:e,wr:i,hr:n,grayThreshold:r}},[s.buffer])})}async capture(e,i){let n;if(je(this),i||(i=t._defaultTemplate),Jt(this,xe,!1,"f"),A(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await B(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Jt(this,Ie,this.maxImageSideLength/o,"f"),i=Math.round(r*Zt(this,Ie,"f")),n=Math.round(s*Zt(this,Ie,"f"))):(i=r,n=s),Zt(this,_e,"f")||Jt(this,_e,document.createElement("canvas"),"f");const a=Zt(this,_e,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Jt(this,Ie,this.maxImageSideLength/o,"f"),i=Math.round(r*Zt(this,Ie,"f")),n=Math.round(s*Zt(this,Ie,"f"))):(i=r,n=s),Zt(this,_e,"f")||Jt(this,_e,document.createElement("canvas"),"f");const a=Zt(this,_e,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Ft();const l=new te;return Pt[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;e.bytes=i.bytes,Zt(this,me,"m",De).call(this,t,e),i.isScanner||Jt(this,Ie,0,"f"),Zt(this,me,"m",Le).call(this,t,e);const n=Date.now();return n-Zt(this,Te,"f")>Zt(this,be,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),Jt(this,Te,n,"f")),l.resolve(t)}catch(i){Ve({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else Ve({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),Lt.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Zt(this,xe,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(je(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await B(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Ft();Pt[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&Ve({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}Ve({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},Lt.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return je(this),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Ve({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}Ve({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},Lt.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,null,2,function(t,e){return e instanceof Array?JSON.stringify(e):e},2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return je(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Ve({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}Ve({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},Lt.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return je(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&Ve({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}Ve({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},Lt.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return je(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&Ve({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}Ve({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},Lt.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return je(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Ve({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}Ve({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},Lt.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return Zt(this,we,"f")||Jt(this,we,new ee(this),"f"),Zt(this,we,"f")}getIntermediateResultManager(){if(je(this),!Zt(this,Oe,"f")&&0!==Ht.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Zt(this,ye,"f")||Jt(this,ye,new re(this),"f"),Zt(this,ye,"f")}static async setGlobalIntraOpNumThreads(t=0){return t>4||t<0?Promise.reject(new RangeError("'intraOpNumThreads' should be between 0 and 4.")):(await Ht.loadWasm(),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();Ve({message:t.message,rj:i,stack:t.stack,functionName:"setGlobalIntraOpNumThreads"})},Lt.postMessage({type:"cvr_setGlobalIntraOpNumThreads",id:n,body:{intraOpNumThreads:t}})}))}async parseRequiredResources(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));Ve({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},Lt.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){je(this),Zt(this,ve,"f")&&this.stopCapturing(),Jt(this,pe,null,"f"),Zt(this,Ce,"f").clear(),Zt(this,Ee,"f").clear(),Zt(this,Se,"f").clear(),Zt(this,ye,"f")._intermediateResultReceiverSet.clear(),Jt(this,Re,!0,"f");let t=Ft();Pt[t]=t=>{t.success||Ve({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},Lt.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Zt(this,pe,"f"),promiseStartScan:Zt(this,ve,"f"),intermediateResultManager:Zt(this,ye,"f"),bufferdItemsManager:Zt(this,we,"f"),resultReceiverSet:Zt(this,Ce,"f"),isaStateListenerSet:Zt(this,Ee,"f"),resultFilterSet:Zt(this,Se,"f"),compressRate:Zt(this,Ie,"f"),canvas:Zt(this,_e,"f"),isScanner:Zt(this,xe,"f"),innerUseTag:Zt(this,Oe,"f"),isDestroyed:Zt(this,Re,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}Ve({message:i.message,rj:e,stack:i.stack,functionName:""})},Lt.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Re=new WeakMap,Ae=new WeakMap,me=new WeakSet,De=function(t,e){var i,n,r,s,o,a,h,l,c,u,d,f;for(let g=0;g{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);Ve({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Pe=async function(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);Ve({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},ke=async function(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);Ve({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},Ne=async function(){let t=Ft();const e=new te;return Pt[t]=async t=>{if(t.success)return e.resolve();Ve({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},Lt.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},We._defaultTemplate="Default",We._isNoOnnx=!1;let Ye=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},He=class{constructor(){this._observedResultUnitTypes=Et.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}};var Xe;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadSingleBarcode",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Xe||(Xe={}));const ze="undefined"==typeof self,qe="function"==typeof importScripts,Ke=(()=>{if(!qe){if(!ze&&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"./"}})();Ht.engineResourcePaths.dce={version:"4.3.3-dev-20251029130621",path:Ke,isInternal:!0},Gt.dce={wasm:!1,js:!1},Vt.dce={};let Ze,Je,$e,Qe,ti,ei=class{static getVersion(){return"4.3.3-dev-20251029130621"}};function ii(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ni(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ze=navigator,Je=Ze.userAgent,$e=Ze.platform,Qe=Ze.mediaDevices),function(){if(!ze){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ze.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:$e,search:"Win"},Mac:{str:$e},Linux:{str:$e}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Je,o=r.search||e,a=r.verStr||Je,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Je,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Je.indexOf("Windows NT")&&(r="HarmonyOS"),ti={browser:i,version:n,OS:r}}ze&&(ti={browser:"ssr",version:0,OS:"ssr"})}();const ri="undefined"!=typeof WebAssembly&&Je&&!(/Safari/.test(Je)&&!/Chrome/.test(Je)&&/\(.+\s11_2_([2-6]).*\)/.test(Je)),si=!("undefined"==typeof Worker),oi=!(!Qe||!Qe.getUserMedia),ai=async()=>{let t=!1;if(oi)try{(await Qe.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===ti.browser&&ti.version>66||"Safari"===ti.browser&&ti.version>13||"OPR"===ti.browser&&ti.version>43||"Edge"===ti.browser&&ti.version;var hi={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some(function(e){return"function"==typeof e.contains&&e.contains(t,!0)})},complexity:function(){return this._objects.reduce(function(t,e){return t+(e.complexity?e.complexity():0)},0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach(function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))}),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,I=-E*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kE)for(var T=1,I=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,R=E.length,A=R;R--;)I=(O=1-(f=E[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(function(t){for(var i=t.slice(0),n={},r=1;r=e})}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach(function(t){t.cancel()}),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter(function(e){return"object"==typeof e.target&&e.target.canvas===t});return e.forEach(function(t){t.cancel()}),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach(function(t){t.cancel()}),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find(function(e){return e.cancel===t})},findAnimationsByTarget:function(t){return t?this.filter(function(e){return e.target===t}):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map(function(t,e){return v[e]-_[e]}):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map(function(t,e){return m(n,_[e],y[e],c)}):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!o){if(!f(w,C,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",S=0,b=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=C.width-r*c,b=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y(function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach(function(e){i[e]=t[e]}),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach(function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s})}(0,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,function(t,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(e){this[e]!==i[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)},this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find(function(e){return!0===t[e]}):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach(function(i){e[i]=t[i]}),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach(function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})}),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter(function(e){return!e.onSelect({e:t})})),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){r.clear(),r._setBgOverlay(n,function(){s?r._enlivenObjects([s],function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)}):r.__setupCanvas.call(r,n,t,o,e)})},i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach(function(t,e){r.insertAt(t,e)}),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],function(e){r[t]=e[0],i[t]=!0,n&&n()}):this["set"+b.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},null,i):e&&e([])},_toDataURL:function(t,e){this.clone(function(i){e(i.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,i){this.clone(function(n){i(n.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(i,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,function(){i.renderAll(),t&&t(i)}),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach(function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])}),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var o=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,function(){var t=s?new o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,o=b.util.sin(n)*r;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach(function(t){r[t]=e[t]}),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl(function(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,function(t){delete t.points,i&&i(t)},"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r}),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter(function(t){return t&&!t.isNeutralState()}),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,function(){var n=new b.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,function(t,n){e&&e(new b.Image(t,i),n)},null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach(function(t){t.applyTo(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(b-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},li={};function ci(t){var e=li[t];if(void 0!==e)return e.exports;var i=li[t]={exports:{}};return hi[t](i,i.exports,ci),i.exports}ci.d=(t,e)=>{for(var i in e)ci.o(e,i)&&!ci.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ci.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ui={};(()=>{let t;ci.d(ui,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ci(653).fabric:{version:"5.2.1"}})();var di,fi,gi,mi,pi=ui.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"}(di||(di={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(fi||(fi={})),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"}(gi||(gi={})),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"}(mi||(mi={}));const _i=t=>"number"==typeof t&&!Number.isNaN(t),vi=t=>"string"==typeof t;var yi,wi,Ci,Ei,Si,bi,Ti,Ii,xi,Oi,Ri;!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"}(Si||(Si={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(bi||(bi={}));let Ai=class{get mediaType(){return new Map([["rect",di.DIMT_RECTANGLE],["quad",di.DIMT_QUADRILATERAL],["text",di.DIMT_TEXT],["arc",di.DIMT_ARC],["image",di.DIMT_IMAGE],["polygon",di.DIMT_POLYGON],["line",di.DIMT_LINE],["group",di.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(ii(this,wi,"f")){case fi.DIS_DEFAULT:return"default";case fi.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"===ii(this,Ci,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===ii(this,Ci,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),ni(this,Ci,t,"f")}get coordinateBase(){return ii(this,Ci,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(yi.add(this),wi.set(this,void 0),Ci.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&&!_i(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(fi.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(fi.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(fi.DIS_SELECTED):this.setState(fi.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){ni(this,wi,t,"f")}getState(){return ii(this,wi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Fi),actionName:"modifyPolygon",pointIndex:i}),t},{}),ni(this,Ii,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map(t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2})),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce(function(t,e,n){return t["p"+n]=new pi.Control({positionHandler:Li,actionHandler:Pi(n>0?n-1:i,Fi),actionName:"modifyPolygon",pointIndex:n}),t},{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=pi.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){ii(this,Ii,"f")&&this.setPolygon(ii(this,Ii,"f"))}setPolygon(t){if(!P(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 ni(this,Ii,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 ii(this,Ii,"f")?JSON.parse(JSON.stringify(ii(this,Ii,"f"))):null}};Ii=new WeakMap;let Ni=class extends Ai{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return ii(this,Oi,"f")}constructor(t,e,i,n){if(super(null,n),xi.set(this,void 0),Oi.set(this,void 0),!N(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new pi.Image(t,{left:e.x,top:e.y}));else{if(!A(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===_.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map(t=>t.split("\t")))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2})),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new pi.Control({positionHandler:Li,actionHandler:Pi(i>0?i-1:n,Fi),actionName:"modifyPolygon",pointIndex:i}),t},{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=pi.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){ii(this,Ui,"f")&&this.setLine(ii(this,Ui,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!M(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 ni(this,Ui,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 ii(this,Ui,"f")?JSON.parse(JSON.stringify(ii(this,Ui,"f"))):null}};Ui=new WeakMap;class Wi extends ki{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Vi.set(this,void 0),!k(t))throw new TypeError("Invalid 'quad'.");ni(this,Vi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){ii(this,Vi,"f")&&this.setQuad(ii(this,Vi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!k(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 ni(this,Vi,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 ii(this,Vi,"f")?JSON.parse(JSON.stringify(ii(this,Vi,"f"))):null}}Vi=new WeakMap;let Yi=class extends Ai{constructor(t){super(new pi.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(fi.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(fi.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("deselected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map(t=>t.getDrawingItem())}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}};const Hi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Xi=t=>!!vi(t)&&""!==t,zi=t=>!(!Hi(t)||"id"in t&&!_i(t.id)||"lineWidth"in t&&!_i(t.lineWidth)||"fillStyle"in t&&!Xi(t.fillStyle)||"strokeStyle"in t&&!Xi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Xi(t.fontFamily)||"fontSize"in t&&!_i(t.fontSize));class qi{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(N(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!D(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Ki,Zi;class Ji{constructor(){Ki.set(this,new Map),Zi.set(this,!1)}get disposed(){return ii(this,Zi,"f")}on(t,e){t=t.toLowerCase();const i=ii(this,Ki,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else ii(this,Ki,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=ii(this,Ki,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=ii(this,Ki,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=ii(this,Ki,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){ni(this,Zi,!0,"f")}}function $i(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 Qi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function tn(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Ki=new WeakMap,Zi=new WeakMap;const en=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};class nn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*r[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return nn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return nn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return nn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,br,Tr,Ir,xr,Or,Rr,Ar,Dr;class Lr{static createDrawingStyle(t){if(!zi(t))throw new Error("Invalid style definition.");let e,i=Lr.USER_START_STYLE_ID;for(;ii(Lr,rn,"f",sn).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in ii(Lr,rn,"f",on))n.hasOwnProperty(t)||(n[t]=ii(Lr,rn,"f",on)[t]);return ii(Lr,rn,"f",sn).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=ii(Lr,rn,"f",sn).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(ii(Lr,rn,"f",sn).values())))}static _updateDrawingStyle(t,e){if(!zi(e))throw new Error("Invalid style definition.");const i=ii(Lr,rn,"f",sn).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}rn=Lr,Lr.STYLE_BLUE_STROKE=1,Lr.STYLE_GREEN_STROKE=2,Lr.STYLE_ORANGE_STROKE=3,Lr.STYLE_YELLOW_STROKE=4,Lr.STYLE_BLUE_STROKE_FILL=5,Lr.STYLE_GREEN_STROKE_FILL=6,Lr.STYLE_ORANGE_STROKE_FILL=7,Lr.STYLE_YELLOW_STROKE_FILL=8,Lr.STYLE_BLUE_STROKE_TRANSPARENT=9,Lr.STYLE_GREEN_STROKE_TRANSPARENT=10,Lr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Lr.USER_START_STYLE_ID=1024,sn={value:new Map([[Lr.STYLE_BLUE_STROKE,{id:Lr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_GREEN_STROKE,{id:Lr.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}],[Lr.STYLE_ORANGE_STROKE,{id:Lr.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}],[Lr.STYLE_YELLOW_STROKE,{id:Lr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_BLUE_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_GREEN_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_ORANGE_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_YELLOW_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Lr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Lr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Lr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},on={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&&(pi.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(pi.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),pi.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},pi.Object.prototype.transparentCorners=!1,pi.Object.prototype.cornerSize=20,pi.Object.prototype.touchCornerSize=100,pi.Object.prototype.cornerColor="rgb(254,142,20)",pi.Object.prototype.cornerStyle="circle",pi.Object.prototype.strokeUniform=!0,pi.Object.prototype.hasBorders=!1,pi.Canvas.prototype.containerClass="",pi.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=pi.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},pi.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;ii&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Mr{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 pi.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])},0)}}),e.on("before:selection:cleared",function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.fabricCanvas.id=e,this.id=e,e){case Mr.DDN_LAYER_ID:n=Lr.getDrawingStyle(Lr.STYLE_BLUE_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_BLUE_STROKE_FILL);break;case Mr.DBR_LAYER_ID:n=Lr.getDrawingStyle(Lr.STYLE_ORANGE_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_ORANGE_STROKE_FILL);break;case Mr.DLR_LAYER_ID:n=Lr.getDrawingStyle(Lr.STYLE_GREEN_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_GREEN_STROKE_FILL);break;default:n=Lr.getDrawingStyle(Lr.STYLE_YELLOW_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_YELLOW_STROKE_FILL)}for(let t of Ai.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Lr.getDrawingStyle(t.styleId);return Lr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems(e=>e._mediaType===t);for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Lr.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Lr.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Lr.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Ai))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ai.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Lr.getDrawingStyle(t.styleId);else{s=Lr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ai.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Lr.getDrawingStyle(t.styleId);else{s=Lr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase()):e=Ai.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Ai.arrStyleSelectors;const n=Lr.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&di.DIMT_RECTANGLE&&n.push("rect"),i&di.DIMT_QUADRILATERAL&&n.push("quad"),i&di.DIMT_TEXT&&n.push("text"),i&di.DIMT_ARC&&n.push("arc"),i&di.DIMT_IMAGE&&n.push("image"),i&di.DIMT_POLYGON&&n.push("polygon"),i&di.DIMT_LINE&&n.push("line");const r=[];e&fi.DIS_DEFAULT&&r.push("default"),e&fi.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Mr.DDN_LAYER_ID=1,Mr.DBR_LAYER_ID=2,Mr.DLR_LAYER_ID=3,Mr.USER_DEFINED_LAYER_BASE_ID=100,Mr.TIP_LAYER_ID=999;class Fr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Mr(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 Pr extends ji{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),an.set(this,void 0),hn.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&ni(this,hn,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},ii(this,an,"f")),"f")}getDuration(){return ii(this,an,"f")}}an=new WeakMap,hn=new WeakMap;class kr{constructor(){ln.add(this),cn.set(this,void 0),un.set(this,void 0),dn.set(this,void 0),fn.set(this,!0),this._drawingLayerManager=new Fr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Mr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Mr.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()!==Mr.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(!(Hi(e=t)&&F(e.topLeftPoint)&&_i(e.width))||e.width<=0||!_i(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;ni(this,cn,JSON.parse(JSON.stringify(t)),"f"),ii(this,cn,"f").coordinateBase||(ii(this,cn,"f").coordinateBase="view"),ni(this,dn,t.duration,"f"),ii(this,ln,"m",_n).call(this)}getTipConfig(){return ii(this,cn,"f")?ii(this,cn,"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()),ni(this,fn,t,"f")}isTipVisible(){return ii(this,fn,"f")}updateTipMessage(t){if(!ii(this,cn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Lr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Mr.TIP_LAYER_ID)||this._createDrawingLayer(Mr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=ii(this,ln,"m",gn).call(this,t,ii(this,cn,"f").topLeftPoint.x,ii(this,cn,"f").topLeftPoint.y,ii(this,cn,"f").width,ii(this,cn,"f").coordinateBase,this._tipStyleId),ii(this,ln,"m",mn).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",ii(this,fn,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),ii(this,un,"f")&&clearTimeout(ii(this,un,"f")),ii(this,dn,"f")>=0&&ni(this,un,setTimeout(()=>{ii(this,ln,"m",pn).call(this)},ii(this,dn,"f")),"f")}}cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,ln=new WeakSet,gn=function(t,e,i,n,r,s){const o=new Pr(t,e,i,n,s);return o.coordinateBase=r,o},mn=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},pn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},_n=function(){if(!this._tip)return;const t=ii(this,cn,"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 Nr extends HTMLElement{constructor(){super(),vn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),ni(this,vn,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return ii(this,vn,"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())}}vn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Nr);class Br extends kr{static get engineResourcePath(){const t=V(Ht.engineResourcePaths);return"DCV"===Ht._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Br._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Br._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Br.engineResourcePath)}static async createInstance(t){const e=new Br;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Br.engineResourcePath)),await e.setUIElement(t||Br.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==ii(this,On,"f")){if(ni(this,On,t,"f"),ii(this,yn,"m",Dn).call(this))ni(this,Sn,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"),!ii(this,Sn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ti.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ni(this,Sn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}ii(this,yn,"m",Dn).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 ii(this,On,"f")}get disposed(){return ii(this,An,"f")}constructor(){super(),yn.add(this),wn.set(this,void 0),Cn.set(this,void 0),En.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",Sn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._poweredBy=null,bn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Tn.set(this,!1),In.set(this,!1),xn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{ii(this,yn,"m",kn).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()&&ii(this,yn,"m",Pn).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Br._onLog&&Br._onLog("window resize event triggered."),ii(this,xn,"f").width===document.documentElement.clientWidth&&ii(this,xn,"f").height===document.documentElement.clientHeight||(ii(this,xn,"f").width=document.documentElement.clientWidth,ii(this,xn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},On.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!ii(this,yn,"m",Dn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout(()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)},0)}),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Rn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{(e=JSON.parse(JSON.stringify(e))).forEach(t=>Br._transformCoordinates(t,i,n,r,s,o,a));const c=new Wi({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]),ii(this,Rn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case ft.CRIT_ORIGINAL_IMAGE:break;case ft.CRIT_BARCODE:m=this.getDrawingLayer(Mr.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,Lr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_TEXT_LINE:m=this.getDrawingLayer(Mr.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,Lr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Mr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Lr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case ft.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(Mr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Lr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case ft.CRIT_PARSED_RESULT:case ft.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}}},An.set(this,!1),this.eventHandler=new Ji,this.eventHandler.on("content:updated",()=>{ii(this,wn,"f")&&clearTimeout(ii(this,wn,"f")),ni(this,wn,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",()=>{ii(this,Cn,"f")&&clearTimeout(ii(this,Cn,"f")),ni(this,Cn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await en(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),ii(this,yn,"m",Dn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ti.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ni(this,Sn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||ii(this,yn,"m",Dn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||ii(this,yn,"m",Dn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||ii(this,yn,"m",kn).call(this),ii(this,yn,"m",Dn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),ii(this,yn,"m",Dn).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;Br._onLog&&Br._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()}));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}ii(this,xn,"f").width=document.documentElement.clientWidth,ii(this,xn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;ii(this,yn,"m",Dn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),ii(this,yn,"m",kn).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,ni(this,Sn,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return ii(this,Sn,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!ii(this,Sn,"f"))return;if(ii(this,Sn,"f").style.objectFit=t,ii(this,yn,"m",Dn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();ii(this,yn,"m",Nn).call(this,e,i),ii(this,yn,"m",Ln).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(ii(this,yn,"m",Dn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=ii(this,Sn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=ii(this,Sn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){D(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):N(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=qi.convert(this.scanRegion,t.width,t.height,this);ni(this,bn,e,"f"),ii(this,En,"f")&&clearTimeout(ii(this,En,"f")),ni(this,En,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}ii(this,yn,"m",Ln).call(this,t,e),ii(this,yn,"m",Nn).call(this,t,e)},0),"f")}getConvertedRegion(){return ii(this,bn,"f")}setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=ii(this,Sn,"f").videoWidth,i=ii(this,Sn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=ii(this,Sn,"f").videoWidth,e=ii(this,Sn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove()),ii(this,Rn,"f").length=0}dispose(){this._unbindUI(),ni(this,An,!0,"f")}}wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Sn=new WeakMap,bn=new WeakMap,Tn=new WeakMap,In=new WeakMap,xn=new WeakMap,On=new WeakMap,Rn=new WeakMap,An=new WeakMap,yn=new WeakSet,Dn=function(){return"disabled"!==this._singleFrameMode},Ln=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)},Mn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Fn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Pn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},kn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Nn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach(e=>t.attachShader(i,e)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);ni(this,Un,{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"),ni(this,Vn,e(t),"f"),ni(this,jn,i(t),"f"),ni(this,Bn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,o,m)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[mi.GREY,mi.GREY32].includes(p)?1:0);let _,v,y=nn.translate(nn.identity(),-1,-1);y=nn.scale(y,2,2),y=nn.scale(y,1/t.canvas.width,1/t.canvas.height),_=nn.translate(y,u,d),_=nn.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=nn.translate(nn.identity(),1,0),v=nn.scale(v,-1,1),v=nn.translate(v,a/i,h/n),v=nn.scale(v,l/i,c/n)):(v=nn.translate(nn.identity(),a/i,h/n),v=nn.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,ii(this,jn,"f"),e),y(t,ii(this,Un,"f"),ii(this,Vn,"f"),ii(this,jn,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){jr._onLog&&jr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return jr._onLog&&jr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===mi.GREY?mi.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return jr._onLog&&jr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(jr._onLog&&(r=Date.now(),jr._onLog("transformPixelFormat(), START: "+r)),e===i)return jr._onLog&&jr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[mi.RGBA,mi.RBGA,mi.GRBA,mi.GBRA,mi.BRGA,mi.BGRA];if(o.includes(e))if(i===mi.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=jr._onLog)||void 0===n||n.call(jr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||mi.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(mi.GREY===y&&w.length{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Vr{static get version(){return"4.3.3-dev-20251029130621"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find(t=>e.includes(t.label.toLowerCase()));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!r.length)return null;const s=r.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(s)return s.deviceId;const o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(ti.OS))return Vr.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(ti.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise(async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise(t=>{g=t}),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise(t=>{setTimeout(t,1e3)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}})}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!ii(this,nr,"f"))return"closed";if("pending"===ii(this,nr,"f"))return"opening";if("fulfilled"===ii(this,nr,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Vr.isStorageAvailable("localStorage")?ni(this,Qn,!0,"f"):(ni(this,Qn,!1,"f"),console.warn("Local storage is unavailable")):ni(this,Qn,!1,"f")}get ifSaveLastUsedCamera(){return ii(this,Qn,"f")}get isVideoPlaying(){return!(!ii(this,Xn,"f")||ii(this,Xn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=ii(this,lr,"f"))||void 0===e||e.removeEventListener("click",ii(this,hr,"f")),null===(i=ii(this,lr,"f"))||void 0===i||i.removeEventListener("touchend",ii(this,hr,"f")),null===(n=ii(this,lr,"f"))||void 0===n||n.removeEventListener("touchmove",ii(this,ar,"f")),ni(this,lr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(ti.OS)?(t.addEventListener("touchend",ii(this,hr,"f")),t.addEventListener("touchmove",ii(this,ar,"f"))):t.addEventListener("click",ii(this,hr,"f")))}get tapFocusEventBoundEl(){return ii(this,lr,"f")}get disposed(){return ii(this,vr,"f")}constructor(t){var e,i;Hn.add(this),Xn.set(this,null),zn.set(this,void 0),this._zoomPreSetting=null,qn.set(this,()=>{"opened"===this.state&&ii(this,fr,"f").fire("resumed",null,{target:this,async:!1})}),Kn.set(this,()=>{ii(this,fr,"f").fire("paused",null,{target:this,async:!1})}),Zn.set(this,void 0),Jn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],$n.set(this,void 0),Qn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,tr.set(this,void 0),er.set(this,!0),ir.set(this,void 0),nr.set(this,void 0),rr.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},sr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(ii(this,Xn,"f")).objectFit,s=this.getResolution(),o=ii(this,Xn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=ii(this,Xn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},or.set(this,!1),ar.set(this,()=>{ni(this,or,!0,"f")}),hr.set(this,async t=>{var e;if(ii(this,or,"f"))return void ni(this,or,!1,"f");if(!ii(this,sr,"f"))return;if(!this.isVideoPlaying)return;if(!ii(this,zn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Vr._onLog&&(c=Date.now());try{await ii(this,Hn,"m",Rr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Vr._onLog)throw Vr._onLog(t),t}Vr._onLog&&Vr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Vr._onLog&&Vr._onLog("Back to continuous focus."),null===(t=ii(this,zn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),ii(this,fr,"f").fire("tapfocus",null,{target:this,async:!1})}),lr.set(this,null),cr.set(this,1),ur.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!ii(this,Xn,"f"))return;const t=ii(this,cr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)ii(this,Xn,"f").style.transform="";else{const e=window.getComputedStyle(ii(this,Xn,"f")).objectFit,i=ii(this,Xn,"f").videoWidth,n=ii(this,Xn,"f").videoHeight,{width:r,height:s}=ii(this,Xn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-ii(this,ur,"f").x),c=h*(1-1/t)*(n/2-ii(this,ur,"f").y);ii(this,Xn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},dr.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===mi.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Vr._onLog&&Vr._onLog("document visible. video paused: "+(null===(t=ii(this,Xn,"f"))||void 0===t?void 0:t.paused)),function(){const t=navigator.userAgent||navigator.vendor||navigator.opera;return!!/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(t)||("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024}())"opened"===this.state&&await ii(this,Hn,"m",Tr).call(this);else if("opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Vr._onLog&&Vr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Vr._onLog&&Vr._onLog("document visible. 1st resume video failed, try open instead.")}e||await ii(this,Hn,"m",Sr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Vr._onLog&&Vr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Vr._onLog&&Vr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await ii(this,Hn,"m",Sr).call(this)}}}else"hidden"===document.visibilityState&&(Vr._onLog&&Vr._onLog("document hidden. video paused: "+(null===(e=ii(this,Xn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),vr.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(()=>{Vr.onWarning&&Vr.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),ni(this,fr,new Ji,"f"),this.imageDataGetter=new jr,document.addEventListener("visibilitychange",ii(this,_r,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",ii(this,qn,"f")),t.addEventListener("pause",ii(this,Kn,"f")),ni(this,Xn,t,"f")}getVideoEl(){return ii(this,Xn,"f")}releaseVideoEl(){var t,e;null===(t=ii(this,Xn,"f"))||void 0===t||t.removeEventListener("play",ii(this,qn,"f")),null===(e=ii(this,Xn,"f"))||void 0===e||e.removeEventListener("pause",ii(this,Kn,"f")),ni(this,Xn,null,"f")}isVideoLoaded(){return!!ii(this,Xn,"f")&&(this.videoSrc?0!==ii(this,Xn,"f").readyState:4===ii(this,Xn,"f").readyState)}async open(){if(ii(this,ir,"f")&&!ii(this,er,"f")){if("pending"===ii(this,nr,"f"))return ii(this,ir,"f");if("fulfilled"===ii(this,nr,"f"))return}ii(this,fr,"f").fire("before:open",null,{target:this}),await ii(this,Hn,"m",Tr).call(this),ii(this,fr,"f").fire("played",null,{target:this,async:!1}),ii(this,fr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;ii(this,fr,"f").fire("before:close",null,{target:this});const t=ii(this,ir,"f");if(ii(this,Hn,"m",Ir).call(this),t&&"pending"===ii(this,nr,"f")){try{await t}catch(t){}if(!1===ii(this,er,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}ni(this,ir,null,"f"),ni(this,nr,null,"f"),ii(this,fr,"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.");ii(this,Xn,"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 ii(this,Xn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof ii(this,Zn,"f").video&&(ii(this,Zn,"f").video={}),delete ii(this,Zn,"f").video.facingMode,ii(this,Zn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&ii(this,er,"f"))){ii(this,fr,"f").fire("before:camera:change",[],{target:this,async:!1}),await ii(this,Hn,"m",br).call(this);try{this.resetSoftwareScale()}catch(t){}return ii(this,Jn,"f")}}async switchToFrontCamera(t){if("object"!=typeof ii(this,Zn,"f").video&&(ii(this,Zn,"f").video={}),(null==t?void 0:t.resolution)&&(ii(this,Zn,"f").video.width={ideal:t.resolution.width},ii(this,Zn,"f").video.height={ideal:t.resolution.height}),delete ii(this,Zn,"f").video.deviceId,ii(this,Zn,"f").video.facingMode={exact:"user"},ni(this,$n,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&ii(this,er,"f"))){ii(this,fr,"f").fire("before:camera:change",[],{target:this,async:!1}),ii(this,Hn,"m",br).call(this);try{this.resetSoftwareScale()}catch(t){}return ii(this,Jn,"f")}}getCamera(){var t;if(ii(this,Jn,"f"))return ii(this,Jn,"f");{let e=(null===(t=ii(this,Zn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"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 ii(this,Zn,"f").video&&(ii(this,Zn,"f").video={}),i?(ii(this,Zn,"f").video.width={exact:t},ii(this,Zn,"f").video.height={exact:e}):(ii(this,Zn,"f").video.width={ideal:t},ii(this,Zn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&ii(this,er,"f"))return null;ii(this,fr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await ii(this,Hn,"m",br).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&ii(this,Xn,"f"))return{width:ii(this,Xn,"f").videoWidth,height:ii(this,Xn,"f").videoHeight};if(ii(this,zn,"f")){const t=ii(this,zn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:ii(this,Xn,"f").videoWidth,height:ii(this,Xn,"f").videoHeight};{const t={width:0,height:0};let e=ii(this,Zn,"f").video.width||0,i=ii(this,Zn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=ii(this,mr,"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=ii(this,Jn,"f"))||void 0===u?void 0:u.deviceId;let e=ii(this,mr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],ii(this,mr,"f").set(d,e),ni(this,rr,!0,"f");try{for(let t of this.detectedResolutions){await ii(this,zn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),ii(this,Hn,"m",wr).call(this);const i=ii(this,zn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw ii(this,Hn,"m",Ir).call(this),ni(this,rr,!1,"f"),t}try{await ii(this,Hn,"m",Sr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{ni(this,rr,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=ii(this,Zn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=ii(this,Zn,"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=ii(this,Zn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=ii(this,mr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],ii(this,mr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");ni(this,Zn,JSON.parse(JSON.stringify(t)),"f"),ni(this,$n,null,"f"),e&&await ii(this,Hn,"m",br).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(ii(this,Zn,"f")))}resetMediaStreamConstraints(){ni(this,Zn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ii(this,zn,"f").getCapabilities?ii(this,zn,"f").getCapabilities():{}}getCameraSettings(){if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ii(this,zn,"f").getSettings()}async turnOnTorch(){if(!ii(this,zn,"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 ii(this,zn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!ii(this,zn,"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 ii(this,zn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await ii(this,zn,"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(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await ii(this,zn,"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(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await ii(this,zn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Ur(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await ii(this,zn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await ii(this,Hn,"m",Rr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await ii(this,zn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}enableTapToFocus(){ni(this,sr,!0,"f")}disableTapToFocus(){ni(this,sr,!1,"f")}isTapToFocusEnabled(){return ii(this,sr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"===this.state){t.centerPoint?ii(this,Hn,"m",Ar).call(this,t.centerPoint):this.resetScaleCenter();try{if(ii(this,Hn,"m",Dr).call(this,ii(this,ur,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}else this._zoomPreSetting=t}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*ii(this,cr,"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(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await ii(this,zn,"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&&ii(this,Hn,"m",Ar).call(this,e),ni(this,cr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return ii(this,cr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();ni(this,ur,{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(ii(this,rr,"f"))return null;const e=Date.now();Vr._onLog&&Vr._onLog("getFrameData() START: "+e);const i=ii(this,Xn,"f").videoWidth,n=ii(this,Xn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=mi.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=ii(this,cr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=ii(this,ur,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(ii(this,Xn,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Vr._onLog&&Vr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:ii(this,dr,"f")}}on(t,e){if(!ii(this,gr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);ii(this,fr,"f").on(t,e)}off(t,e){ii(this,fr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),ii(this,fr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",ii(this,_r,"f")),ni(this,vr,!0,"f")}}var Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,Ss;Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,Hn=new WeakSet,yr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(ii(this,$n,"f"))delete t.video.facingMode,t.video.deviceId={exact:ii(this,$n,"f")};else if(this.ifSaveLastUsedCamera&&Vr.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(ti.OS)?(await this._getCameras(!1),ii(this,Hn,"m",wr).call(this),e=Vr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(ti.OS)||(await this._getCameras(!1),ii(this,Hn,"m",wr).call(this),e=Vr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},wr=function(){if(ii(this,er,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Cr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Vr._onLog&&Vr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise(t=>setTimeout(t,r)),ii(this,Hn,"m",wr).call(this));try{Vr._onLog&&Vr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),ii(this,Hn,"m",wr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Vr._onLog&&Vr._onLog(t.message||t)}}};if(await r(t),!n&&"object"==typeof t.video&&!n){const e=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let i of e)try{n=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:i.deviceId}}});break}catch(t){continue}}if(!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach(t=>{t.stop()}),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Er=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),ni(this,zn,null,"f")},Sr=async function(){ni(this,er,!1,"f");const t=ni(this,tr,Symbol(),"f");if(ii(this,ir,"f")&&"pending"===ii(this,nr,"f")){try{await ii(this,ir,"f")}catch(t){}ii(this,Hn,"m",wr).call(this)}if(t!==ii(this,tr,"f"))return;const e=ni(this,ir,(async()=>{ni(this,nr,"pending","f");try{if(this.videoSrc){if(!ii(this,Xn,"f"))throw new Error("'videoEl' should be set.");await Vr.playVideo(ii(this,Xn,"f"),this.videoSrc,this.cameraOpenTimeout),ii(this,Hn,"m",wr).call(this)}else{let t=await ii(this,Hn,"m",yr).call(this);ii(this,Hn,"m",Er).call(this);let e=await ii(this,Hn,"m",Cr).call(this,t);await this._getCameras(!1),ii(this,Hn,"m",wr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=ii(this,Zn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(ii(this,$n,"f")||this.ifSaveLastUsedCamera&&Vr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Vr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:s},e=await ii(this,Hn,"m",Cr).call(this,t),ii(this,Hn,"m",wr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(ni(this,$n,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Vr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",ii(this,$n,"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))))),ii(this,Xn,"f")&&(await Vr.playVideo(ii(this,Xn,"f"),e,this.cameraOpenTimeout),ii(this,Hn,"m",wr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&ni(this,zn,s[0],"f"),ni(this,Jn,r,"f")}}catch(t){throw ii(this,Hn,"m",Ir).call(this),ni(this,nr,null,"f"),t}ni(this,nr,"fulfilled","f")})(),"f");return e},br=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=ii(this,Jn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await ii(this,Hn,"m",Sr).call(this);const n=this.getResolution();e&&e!==ii(this,Jn,"f").deviceId&&ii(this,fr,"f").fire("camera:changed",[ii(this,Jn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||ii(this,fr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),ii(this,fr,"f").fire("played",null,{target:this,async:!1})},Tr=async function(){let t=0;for(;Vr._tryToReopenTime>=t++;){try{await ii(this,Hn,"m",Sr).call(this)}catch(t){await new Promise(t=>setTimeout(t,300));continue}break}},Ir=function(){ii(this,Hn,"m",Er).call(this),ni(this,Jn,null,"f"),ii(this,Xn,"f")&&(ii(this,Xn,"f").srcObject=null,this.videoSrc&&(ii(this,Xn,"f").pause(),ii(this,Xn,"f").currentTime=0)),ni(this,er,!0,"f");try{this.resetSoftwareScale()}catch(t){}},xr=async function t(e,i){const n=t=>{if(!ii(this,zn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){ii(this,zn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Ur(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await ii(this,zn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise(t=>{setTimeout(t,r)}),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(ii(this,Xn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:mi.RGBA,bufferContainer:d}))return ii(this,Hn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await ii(this,Hn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await ii(this,Hn,"m",xr).call(this,e,c);if(a>h)return await ii(this,Hn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await ii(this,Hn,"m",t).call(this,e,o,a,c,h);let u=await ii(this,Hn,"m",xr).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!==ii(this,cr,"f")){const t=ii(this,cr,"f"),e=ii(this,ur,"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 n=Ur(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ur(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ur(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await ii(this,Hn,"m",xr).call(this,t,s),a=await ii(this,Hn,"m",xr).call(this,t,r),h=await ii(this,Hn,"m",xr).call(this,t,n);if(a>h&&ho&&a>o){let e=await ii(this,Hn,"m",xr).call(this,t,i);const r=await ii(this,Hn,"m",Or).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await ii(this,Hn,"m",Or).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Ar=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");ni(this,ur,{x:i,y:n},"f")},Dr=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},Vr.browserInfo=ti,Vr._tryToReopenTime=4,Vr.onWarning=null===(Yn=null===window||void 0===window?void 0:window.console)||void 0===Yn?void 0:Yn.warn;class bs{constructor(t){Gr.add(this),Wr.set(this,void 0),Yr.set(this,0),Hr.set(this,void 0),Xr.set(this,0),zr.set(this,!1),ni(this,Wr,t,"f")}startCharging(){ii(this,zr,"f")||(bs._onLog&&bs._onLog("start charging."),ii(this,Gr,"m",Kr).call(this),ni(this,zr,!0,"f"))}stopCharging(){ii(this,Hr,"f")&&clearTimeout(ii(this,Hr,"f")),ii(this,zr,"f")&&(bs._onLog&&bs._onLog("stop charging."),ni(this,Yr,Date.now()-ii(this,Xr,"f"),"f"),ni(this,zr,!1,"f"))}}Wr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,Gr=new WeakSet,qr=function(){Ht.cfd(1),bs._onLog&&bs._onLog("charge 1.")},Kr=function t(){0==ii(this,Yr,"f")&&ii(this,Gr,"m",qr).call(this),ni(this,Xr,Date.now(),"f"),ii(this,Hr,"f")&&clearTimeout(ii(this,Hr,"f")),ni(this,Hr,setTimeout(()=>{ni(this,Yr,0,"f"),ii(this,Gr,"m",t).call(this)},ii(this,Wr,"f")-ii(this,Yr,"f")),"f")};class Ts{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-ii(this,Zr,"f",Qr)<100)){if(ni(this,Zr,e,"f",Qr),ii(this,Zr,"f",Jr).size&&(t=ii(this,Zr,"f",Jr).values().next().value,this.beepSoundSource==t.src?(ii(this,Zr,"f",Jr).delete(t),t.play()):t=null),!t)if(ii(this,Zr,"f",$r).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{ii(this,Zr,"f",$r).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,ii(this,Zr,"f",$r).delete(t),ii(this,Zr,"f",Jr).add(t)})}else ii(this,Zr,"f",ts)||(ni(this,Zr,!0,"f",ts),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&ii(this,Zr,"f",$r).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ts.vibrateDuration)}}}Zr=Ts,Jr={value:new Set},$r={value:new Set},Qr={value:0},ts={value:!1},Ts.allowBeep=!0,Ts.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Ts.allowVibrate=!0,Ts.vibrateDuration=300;const Is=new Map([[mi.GREY,_.IPF_GRAYSCALED],[mi.RGBA,_.IPF_ABGR_8888]]),xs="function"==typeof BigInt?t=>BigInt(t):t=>t,Os=(xs("0x00"),xs("0xFFFFFFFFFFFFFFFF"),xs("0xFE3BFFFF"),xs("0x003007FF")),Rs=(xs("0x0003F800"),xs("0x1"),xs("0x2"),xs("0x4"),xs("0x8"),xs("0x10"),xs("0x20"),xs("0x40"),xs("0x80"),xs("0x100"),xs("0x200"),xs("0x400"),xs("0x800"),xs("0x1000"),xs("0x2000"),xs("0x4000"),xs("0x8000"),xs("0x10000"),xs("0x20000"),xs("0x00040000"),xs("0x01000000"),xs("0x02000000"),xs("0x04000000")),As=xs("0x08000000");xs("0x10000000"),xs("0x20000000"),xs("0x40000000"),xs("0x00080000"),xs("0x80000000"),xs("0x100000"),xs("0x200000"),xs("0x400000"),xs("0x800000"),xs("0x1000000000"),xs("0x3F0000000000000"),xs("0x100000000"),xs("0x10000000000000"),xs("0x20000000000000"),xs("0x40000000000000"),xs("0x80000000000000"),xs("0x100000000000000"),xs("0x200000000000000"),xs("0x200000000"),xs("0x400000000"),xs("0x800000000"),xs("0xC00000000"),xs("0x2000000000"),xs("0x4000000000");class Ds extends ht{static set _onLog(t){ni(Ds,is,t,"f",ns),Vr._onLog=t,bs._onLog=t}static get _onLog(){return ii(Ds,is,"f",ns)}static async detectEnvironment(){return await(async()=>({wasm:ri,worker:si,getUserMedia:oi,camera:await ai(),browser:ti.browser,version:ti.version,OS:ti.OS}))()}static async testCameraAccess(){const t=await Vr.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 Br))throw new TypeError("Invalid view.");if(!Ds._isRTU&&(null===(e=Vt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=Vt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await Ht.loadWasm(),await Vt.license.dynamsoft()}const n=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)),n}get isEnableMirroring(){return this._isEnableMirroring}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");ni(this,as,t,"f")}get singleFrameMode(){return ii(this,as,"f")}get _isFetchingStarted(){return ii(this,fs,"f")}get disposed(){return ii(this,vs,"f")}constructor(t){if(super(),es.add(this),rs.set(this,"closed"),ss.set(this,void 0),os.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,as.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},hs.set(this,(t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?mi.GREY:mi.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===mi.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:Is.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:ii(this,ls,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():qi.convert(ii(this,us,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=ii(this,hs,"f").call(this,t,t.width,t.height,e);ii(this,ss,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ls.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===_.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ti.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",()=>{ii(this,_s,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("camera:changed",()=>{this.clearBuffer()}),this._on("before:resolution:change",()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("resolution:changed",()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})}),this._on("paused",()=>{ii(this,_s,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{ii(this,ms,"f").tapToFocus&&ii(this,_s,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(ii(this,es,"m",ys).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Ds._onLog&&(Ds._onLog("intermediateResultUnits:"),Ds._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Et.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Et.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Ds._onLog&&(Ds._onLog("hasLocalizedBarcodes:"),Ds._onLog(h)),ii(this,ms,"f").autoZoom||ii(this,ms,"f").enhancedFocus)if(a)ii(this,ps,"f").autoZoomInFrameArray.length=0,ii(this,ps,"f").autoZoomOutFrameCount=0,ii(this,ps,"f").frameArrayInIdealZoom.length=0,ii(this,ps,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),ii(this,ms,"f").autoZoom&&ii(this,_s,"f").startCharging()},a=async t=>{await this.setFocus(t),ii(this,ms,"f").enhancedFocus&&ii(this,_s,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-ii(this,ps,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+ii(this,ps,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-ii(this,ps,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+ii(this,ps,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Ds._onLog&&(Ds._onLog("detectionArea:"),Ds._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Qi(a.y-i)>0&&Qi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(tn([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||tn([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||tn([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||tn([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Br._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Ds._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Lr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new ki({points:i},e);t.addDrawingItems([r])}}}if(Ds._onLog&&(Ds._onLog("intersectedResults:"),Ds._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==Rs||t.possibleFormats==As);if(t.length||(t=s.filter(t=>t.possibleFormats==Os),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{}),ii(this,ps,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=ii(this,ps,"f").autoZoomInFrameLimit[1]){ii(this,ps,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,ii(this,ps,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/ii(this,ps,"f").autoZoomInMaxTimes),ii(this,ps,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(ii(this,ps,"f").minValue,u),u=Math.min(ii(this,ps,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(ii(this,ps,"f").autoZoomInFrameArray.length=0,ii(this,ps,"f").frameArrayInIdealZoom.push(!0),ii(this,ps,"f").frameArrayInIdealZoom.splice(0,ii(this,ps,"f").frameArrayInIdealZoom.length-ii(this,ps,"f").frameLimitInIdealZoom[0]),ii(this,ps,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=ii(this,ps,"f").frameLimitInIdealZoom[1]&&(ii(this,ps,"f").frameArrayInIdealZoom.length=0,ii(this,ms,"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(!ii(this,ms,"f").autoZoom&&ii(this,ms,"f").enhancedFocus&&(ii(this,ps,"f").autoFocusFrameArray.push(!0),ii(this,ps,"f").autoFocusFrameArray.splice(0,ii(this,ps,"f").autoFocusFrameArray.length-ii(this,ps,"f").autoFocusFrameLimit[0]),ii(this,ps,"f").autoFocusFrameArray.filter(t=>!0===t).length>=ii(this,ps,"f").autoFocusFrameLimit[1])){ii(this,ps,"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(ii(this,ms,"f").autoZoom){if(ii(this,ps,"f").autoZoomInFrameArray.push(!1),ii(this,ps,"f").autoZoomInFrameArray.splice(0,ii(this,ps,"f").autoZoomInFrameArray.length-ii(this,ps,"f").autoZoomInFrameLimit[0]),ii(this,ps,"f").autoZoomOutFrameCount++,ii(this,ps,"f").frameArrayInIdealZoom.push(!1),ii(this,ps,"f").frameArrayInIdealZoom.splice(0,ii(this,ps,"f").frameArrayInIdealZoom.length-ii(this,ps,"f").frameLimitInIdealZoom[0]),ii(this,ps,"f").autoZoomOutFrameCount>=ii(this,ps,"f").autoZoomOutFrameLimit){ii(this,ps,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*ii(this,ps,"f").autoZoomOutStepRate,ii(this,ps,"f").autoZoomOutMinStep);n=Math.max(ii(this,ps,"f").minValue,n),n=Math.min(ii(this,ps,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}ii(this,ms,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!ii(this,ms,"f").autoZoom&&ii(this,ms,"f").enhancedFocus&&(ii(this,ps,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},ni(this,_s,new bs(1e4),"f"),this.getColourChannelUsageType()===p.CCUT_AUTO&&this.setColourChannelUsageType(p.CCUT_Y_CHANNEL_ONLY),this.setPixelFormat(_.IPF_GRAYSCALED)}setCameraView(t){if(!(t instanceof Br))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),ii(this,es,"m",ys).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;ii(this,es,"m",ys).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return ii(this,es,"m",ys).call(this)?ii(this,rs,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,ii(this,es,"m",ys).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(ii(this,es,"m",ys).call(this));else{try{await this.cameraManager.open(),ni(this,os,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=Ts.allowBeep?"":"none"),a&&(a.style.display=Ts.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=Ts.allowVibrate?"":"none"),l&&(l.style.display=Ts.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const C=()=>{Ts.allowBeep=!Ts.allowBeep,o&&(o.style.display=Ts.allowBeep?"":"none"),a&&(a.style.display=Ts.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",C);const E=()=>{Ts.allowVibrate=!Ts.allowVibrate,h&&(h.style.display=Ts.allowVibrate?"":"none"),l&&(l.style.display=Ts.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",E);const S=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==ti?void 0:ti.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",C);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",E);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return ni(this,rs,"open","f"),e&&(e._innerComponent.style.display="",ii(this,es,"m",ys).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),ii(this,ss,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),ii(this,es,"m",ys).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}ni(this,rs,"closed","f"),ii(this,_s,"f").stopCharging(),e&&(e._innerComponent.style.display="none",ii(this,es,"m",ys).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),ii(this,ss,"f").fire("closed",null,{target:this,async:!1})}pause(){if(ii(this,es,"m",ys).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!ii(this,es,"m",ys).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(ii(this,es,"m",ys).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch(()=>{});const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),this.toggleMirroring(this._isEnableMirroring),ii(this,us,"f")&&this.setScanRegion(ii(this,us,"f")),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ii(this,ss,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ii(this,ss,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(ii(this,es,"m",ys).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(ii(this,es,"m",ys).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(_.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Ds._onLog)||void 0===t||t.call(Ds,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(ii(this,es,"m",ys).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(ii(this,es,"m",ys).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(ii(this,es,"m",ys).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(ii(this,es,"m",ys).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(ii(this,es,"m",ys).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(ii(this,es,"m",ys).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){ii(this,ps,"f").minValue=t.min,ii(this,ps,"f").maxValue=t.max}getAutoZoomRange(){return{min:ii(this,ps,"f").minValue,max:ii(this,ps,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=Vt.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&gi.EF_ENHANCED_FOCUS&&(ii(this,ms,"f").enhancedFocus=!0),t&gi.EF_AUTO_ZOOM&&(ii(this,ms,"f").autoZoom=!0),t&gi.EF_TAP_TO_FOCUS&&(ii(this,ms,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&gi.EF_ENHANCED_FOCUS&&(ii(this,ms,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&gi.EF_AUTO_ZOOM&&(ii(this,ms,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&gi.EF_TAP_TO_FOCUS&&(ii(this,ms,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),ii(this,es,"m",Cs).call(this)&&ii(this,es,"m",ws).call(this)||ii(this,_s,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");ni(this,us,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(ii(this,us,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");ni(this,cs,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||ii(this,es,"m",ys).call(this))}startFetching(){if(ii(this,es,"m",ys).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");ii(this,fs,"f")||(ni(this,fs,!0,"f"),ii(this,es,"m",Es).call(this))}stopFetching(){ii(this,fs,"f")&&(Ds._onLog&&Ds._onLog("DCE: stop fetching loop: "+Date.now()),ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),ni(this,fs,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(ii(this,es,"m",ys).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i,n;if(i=qi.convert(ii(this,us,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");if(i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y),ii(this,us,"f")&&!t)n={sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};else{const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});n={sx:t.x,sy:t.y,sWidth:t.width,sHeight:t.height,dWidth:t.width,dHeight:t.height}}const r=Math.max(n.dWidth,n.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;n.dWidth>n.dHeight?(n.dWidth=this.canvasSizeLimit,n.dHeight=Math.round(n.dHeight*t)):(n.dWidth=Math.round(n.dWidth*t),n.dHeight=this.canvasSizeLimit)}const s=this.cameraManager.getFrameData({position:n,pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?mi.GREY:mi.RGBA,isEnableMirroring:this._isEnableMirroring});if(!s)return null;let o;o=s.pixelFormat===mi.GREY?s.width:4*s.width;let a=!0;return 0===n.sx&&0===n.sy&&n.sWidth===e.width&&n.sHeight===e.height&&(a=!1),{bytes:s.data,width:s.width,height:s.height,stride:o,format:Is.get(s.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:n.sx,top:n.sy,right:n.sx+n.sWidth,bottom:n.sy+n.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:s.width,currentHeight:s.height,timeSpent:s.timeSpent,timeStamp:s.timeStamp},toCanvas:ii(this,ls,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,ii(this,fs,"f")&&(ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),ni(this,gs,setTimeout(()=>{this.disposed||ii(this,es,"m",Es).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){ni(this,ds,t,"f")}getPixelFormat(){return ii(this,ds,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(ii(this,es,"m",ys).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",()=>{t&&this.open(),e.remove()},{once:!0})}),e.addEventListener("change",async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=qi.convert(ii(this,us,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=ii(this,hs,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=this.convertToContainCoordinates(t),i=ii(this,es,"m",Ss).call(this,e);return{x:i.pageX,y:i.pageY}}convertToClientCoordinates(t){const e=this.convertToContainCoordinates(t),i=ii(this,es,"m",Ss).call(this,e);return{x:i.clientX,y:i.clientY}}convertToScanRegionCoordinates(t){if(!ii(this,us,"f"))return JSON.parse(JSON.stringify(t));const e=this.convertToContainCoordinates(t);if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});ni(this,os,t||ii(this,os,"f"),"f")}let i,n,r=ii(this,us,"f").left||ii(this,us,"f").x||0,s=ii(this,us,"f").top||ii(this,us,"f").y||0;if(!ii(this,us,"f").isMeasuredInPercentage)return{x:e.x-(r+ii(this,os,"f").x),y:e.y-(s+ii(this,os,"f").y)};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ii(this,es,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ii(this,es,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(ii(this,es,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");i=t.width,n=t.height}else i=ii(this,os,"f").width,n=ii(this,os,"f").height;return{x:e.x-(Math.round(r*i/100)+ii(this,os,"f").x),y:e.y-(Math.round(s*n/100)+ii(this,os,"f").y)}}convertToContainCoordinates(t){if("contain"===this.cameraView.getVideoFit())return t;const e=this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),i=JSON.parse(JSON.stringify(t));return D(ii(this,us,"f"))?ii(this,us,"f").isMeasuredInPercentage?(i.x=e.width*(ii(this,us,"f").left/100)+e.x+t.x,i.y=e.height*(ii(this,us,"f").top/100)+e.y+t.y):(i.x=ii(this,us,"f").left+e.x+t.x,i.y=ii(this,us,"f").top+e.y+t.y):ii(this,us,"f").isMeasuredInPercentage?(i.x=e.width*(ii(this,us,"f").x/100)+e.x+t.x,i.y=e.height*(ii(this,us,"f").y/100)+e.y+t.y):(i.x=ii(this,us,"f").x+e.x+t.x,i.y=ii(this,us,"f").y+e.y+t.y),i}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),ni(this,vs,!0,"f")}}var Ls,Ms,Fs,Ps,ks,Ns,Bs,js;is=Ds,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,es=new WeakSet,ys=function(){return"disabled"!==this.singleFrameMode},ws=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Cs=function(){for(let t in ii(this,ms,"f"))if(1==ii(this,ms,"f")[t])return!0;return!1},Es=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!ii(this,fs,"f"))return ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),void ni(this,gs,setTimeout(()=>{this.disposed||ii(this,es,"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=ii(this,cs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=ii(this,cs,"f"))||void 0===t||t.onErrorReceived(mt.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()),ii(this,ss,"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 m.BOPM_BLOCK:break;case m.BOPM_UPDATE:e()}else e();ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),ni(this,gs,setTimeout(()=>{this.disposed||ii(this,es,"m",t).call(this)},this.fetchInterval),"f")},Ss=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ii(this,es,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ii(this,es,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(ii(this,es,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(ii(this,Ps,"f")||ni(this,Ps,new Us,"f"),!ii(this,Ps,"f").magnifierCanvas)return;document.body.contains(ii(this,Ps,"f").magnifierCanvas)||(ii(this,Ps,"f").magnifierCanvas.style.position="fixed",ii(this,Ps,"f").magnifierCanvas.style.boxSizing="content-box",ii(this,Ps,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(ii(this,Ps,"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 ii(this,Ns,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];ii(this,Ps,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(ii(this,Ps,"f").magnifierCanvas.style.left="auto",ii(this,Ps,"f").magnifierCanvas.style.top="0",ii(this,Ps,"f").magnifierCanvas.style.right="0"):(ii(this,Ps,"f").magnifierCanvas.style.left="0",ii(this,Ps,"f").magnifierCanvas.style.top="0",ii(this,Ps,"f").magnifierCanvas.style.right="auto")}ii(this,Ps,"f").show()}),Ns.set(this,()=>{ii(this,Ps,"f")&&ii(this,Ps,"f").hide()}),Bs.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await en(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(A(t)){ni(this,Fs,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===_.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Ys){if(!Gs&&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"./"}})(),Xs=t=>t&&"object"==typeof t&&"function"==typeof t.then,zs=(async()=>{})().constructor;let qs=class extends zs{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xs(t)?e=t:"function"==typeof t&&(e=new zs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Xs(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ks=" is not allowed to change after `createInstance` or `loadWasm` is called.",Zs=!Gs&&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"))||"",Js=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ks);i._license=e}};!Gs&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const $s=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=$s(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ks);i._licenseServer=e}},to=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ks);i._deviceFriendlyName=e}};let eo,io,no,ro,so;"undefined"!=typeof navigator&&(eo=navigator,io=eo.userAgent,no=eo.platform,ro=eo.mediaDevices),function(){if(!Gs){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:eo.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:no,search:"Win"},Mac:{str:no},Linux:{str:no}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||io,o=r.search||e,a=r.verStr||io,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||io,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=io.indexOf("Windows NT")&&(r="HarmonyOS"),so={browser:i,version:n,OS:r}}Gs&&(so={browser:"ssr",version:0,OS:"ssr"})}(),ro&&ro.getUserMedia,"Chrome"===so.browser&&so.version>66||"Safari"===so.browser&&so.version>13||"OPR"===so.browser&&so.version>43||"Edge"===so.browser&&so.version;const oo=()=>(Ht.loadWasm(),Dt("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=ho;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=$s(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Ws.crypto||(s="Please upgrade your browser to support online key."),Ws.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Ks)})(),o=new qs;ho._pLoad.task=o,(async()=>{try{await ho._pLoad}catch(t){}})();let a=Ft();Pt[a]=e=>{if(e.message&&ho._onAuthMessage){let t=ho._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(kt&&kt("init license success"),e.message&&console.warn(e.message),Ht._bSupportIRTModule=e.bSupportIRTModule,Ht._bSupportDce4Module=e.bSupportDce4Module,ho.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=V(Ht.engineResourcePaths),i=("DCV"===Ht._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:ho._bNeverShowDialog,engineResourcePath:i,_onLog:kt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await At("core");const h=await Ht.getModuleVersion();Lt.postMessage({type:"license_dynamsoft",body:{v:"DCV"===Ht._bundleEnv?h.CVR.replace(/\.\d+$/,""):h.DBR.replace(/\.\d+$/,""),brtk:!!t,bptk:1===t,l:e,os:so,fn:ho.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),ho.bCallInitLicense=!0,await o}));let ao;Vt.license={},Vt.license.dynamsoft=oo,Vt.license.getAR=async()=>{{let t=Rt.dynamsoft_inited;t&&t.isRejected&&await t}return Lt?new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){delete i.success;{let t=ho.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)}},Lt.postMessage({type:"license_getAR",id:i})}):null};let ho=class t{static setLicenseServer(e){Qs(t,e)}static get license(){return this._license}static set license(e){Js(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Qs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){to(t,e)}static initLicense(e,i){if(Js(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return oo()}static setDeviceFriendlyName(e){to(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await Dt("dynamsoft_uuid",async()=>{await Ht.loadWasm();let t=new qs,e=Ft();Pt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Lt.postMessage({type:"license_getDeviceUUID",id:e}),ao=await t}),ao))()}};ho._pLoad=new qs,ho.bPassValidation=!1,ho.bCallInitLicense=!1,ho._license=Zs,ho._licenseServer=[],ho._deviceFriendlyName="",Ht.engineResourcePaths.license={version:"4.2.20-dev-20251029130543",path:Hs,isInternal:!0},Gt.license={wasm:!0,js:!0},Vt.license.LicenseManager=ho;const lo="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,lo)<0&&(Ht.engineResourcePaths.std={version:lo,path:(t=>{if(null==t&&(t="./"),Gs||Ys);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Hs+`../../dynamsoft-capture-vision-std@${lo}/dist/`),isInternal:!0});let co=class{static getVersion(){return`4.2.20-dev-20251029130543(Worker: ${Ut.license&&Ut.license.worker||"Not Loaded"}, Wasm: ${Ut.license&&Ut.license.wasm||"Not Loaded"})`}};const uo=()=>window.matchMedia("(orientation: landscape)").matches,fo=t=>Object.prototype.toString.call(t).slice(8,-1);function go(t,e){for(const i in e)"Object"===fo(e[i])&&i in t?go(t[i],e[i]):t[i]=e[i];return t}function mo(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function po(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;ie.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const vo="undefined"==typeof self,yo="function"==typeof importScripts,wo=(()=>{if(!yo){if(!vo&&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"./"}})(),Co=t=>{if(null==t&&(t="./"),vo||yo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Ht.engineResourcePaths.utility={version:"2.2.20-dev-20251029130550",path:wo,isInternal:!0},Gt.utility={js:!0,wasm:!0};const Eo="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,Eo)<0&&(Ht.engineResourcePaths.std={version:Eo,path:Co(wo+`../../dynamsoft-capture-vision-std@${Eo}/dist/`),isInternal:!0});const So="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,So)<0)&&(Ht.engineResourcePaths.dip={version:So,path:Co(wo+`../../dynamsoft-image-processing@${So}/dist/`),isInternal:!0});let bo=class{static getVersion(){return`2.2.20-dev-20251029130550(Worker: ${Ut.utility&&Ut.utility.worker||"Not Loaded"}, Wasm: ${Ut.utility&&Ut.utility.wasm||"Not Loaded"})`}};function To(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const Io="undefined"==typeof self,xo="function"==typeof importScripts,Oo=(()=>{if(!xo){if(!Io&&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"./"}})(),Ro=t=>{if(null==t&&(t="./"),Io||xo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Ht.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:Oo,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const Ao="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,Ao)<0&&(Ht.engineResourcePaths.std={version:Ao,path:Ro(Oo+`../../dynamsoft-capture-vision-std@${Ao}/dist/`),isInternal:!0});const Do="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,Do)<0)&&(Ht.engineResourcePaths.dip={version:Do,path:Ro(Oo+`../../dynamsoft-image-processing@${Do}/dist/`),isInternal:!0});const Lo={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Mo,Fo,Po,ko,No;(No=Mo||(Mo={}))[No.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",No[No.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",No[No.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Fo||(Fo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(Po||(Po={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(ko||(ko={}));const Bo=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:_.IPF_ABGR_8888}};function jo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Go(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Ho(t){let e=0;for(let i=0;i0}function zo(t,e){for(let i=0;i<4;i++)if(!Xo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}function qo(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Go(r)[3],h=Go(r)[1],l=Go(s)[3],c=Go(s)[1];let u,d=0;if(u=Math.max(Math.abs(Vo(a,e.points[0])),Math.abs(Vo(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Vo(h,e.points[1])),Math.abs(Vo(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Vo(l,t.points[0])),Math.abs(Vo(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Vo(c,t.points[1])),Math.abs(Vo(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Wo(Go(r)[0]),g=Wo(Go(r)[2]),m=Wo(Go(s)[0]),p=Wo(Go(s)[2]),_=Uo(f,p),v=Uo(m,g),y=_>v,w=Math.min(_,v),C=Uo(f,g),E=Uo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(zo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(zo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(zo(t,this.location.points[e]))return!0;if(zo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Vo(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Yo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{jo(e,t)&&i.push(t)}),e.forEach(e=>{jo(t,e)&&i.push(e)}),Ho(function(t){if(t.length<=1)return t;t.sort((t,e)=>t.x-e.x||t.y-e.y);const e=t.shift();return t.sort((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x)),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}var Zo,Jo,$o,Qo,ta;const ea={barcode:2,text_line:4,detected_quad:8,deskewed_image:16,enhanced_image:64},ia=t=>Object.values(ea).includes(t)||ea.hasOwnProperty(t),na=(t,e)=>"string"==typeof t?e[ea[t]]:e[t],ra=(t,e,i)=>{"string"==typeof t?e[ea[t]]=i:e[t]=i},sa=(t,e,i)=>{const n=[{type:ft.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:ft.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class oa{constructor(){this.verificationEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!0,[ft.CRIT_DETECTED_QUAD]:!0,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1},this.duplicateFilterEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1},this.duplicateForgetTime={[ft.CRIT_BARCODE]:3e3,[ft.CRIT_TEXT_LINE]:3e3,[ft.CRIT_DETECTED_QUAD]:3e3,[ft.CRIT_DESKEWED_IMAGE]:3e3,[ft.CRIT_ENHANCED_IMAGE]:3e3},Zo.set(this,new Map),Jo.set(this,new Map),$o.set(this,new Map),Qo.set(this,new Map),ta.set(this,new Map),this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,this.latestOverlappingEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[ft.CRIT_BARCODE]:this.crossVerificationFrames,[ft.CRIT_TEXT_LINE]:this.crossVerificationFrames,[ft.CRIT_DETECTED_QUAD]:this.crossVerificationFrames,[ft.CRIT_DESKEWED_IMAGE]:this.crossVerificationFrames},Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),sa(this,t,ft.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{sa(this,t,ft.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){To(this,Zo,"f").forEach((t,e)=>{ra(e,this.verificationEnabled,t)}),To(this,Jo,"f").forEach((t,e)=>{ra(e,this.duplicateFilterEnabled,t)}),To(this,$o,"f").forEach((t,e)=>{ra(e,this.duplicateForgetTime,t)}),To(this,Qo,"f").forEach((t,e)=>{ra(e,this.latestOverlappingEnabled,t)}),To(this,ta,"f").forEach((t,e)=>{ra(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){ia(t)&&To(this,Zo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!ia(t)&&na(t,this.verificationEnabled)}enableResultDeduplication(t,e){ia(t)&&(e&&this.enableLatestOverlapping(t,!1),To(this,Jo,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!ia(t)&&na(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){ia(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),To(this,$o,"f").set(t,e))}getDuplicateForgetTime(t){return ia(t)?na(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[ft.CRIT_BARCODE,ft.CRIT_TEXT_LINE,ft.CRIT_DETECTED_QUAD,ft.CRIT_DESKEWED_IMAGE,ft.CRIT_ENHANCED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Lo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Lo.BF_GS1_DATABAR))!=BigInt(0);return new Ko(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Lo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Lo.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}f.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),d.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}var aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ca,Ea,Sa,ba,Ta,Ia,xa,Oa,Ra,Aa,Da,La,Ma,Fa,Pa,ka,Na,Ba,ja,Ua,Va,Ga;Zo=new WeakMap,Jo=new WeakMap,$o=new WeakMap,Qo=new WeakMap,ta=new WeakMap;class Wa{async readFromFile(t){return await Bo(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=X(t);return G(n,e,i)}async readFromMemory(t){if(!To(Wa,aa,"f",ha).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=To(Wa,aa,"f",ha).get(t);return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{var i,n;if(e.success)return function(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");r?r.value=i:e.set(t,i)}(i=Wa,aa,(n=To(i,aa,"f",la),++n),0,la),To(Wa,aa,"f",ha).set(To(Wa,aa,"f",la),JSON.parse(e.memery)),t(To(Wa,aa,"f",la));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}aa=Wa,ha={value:new Map},la={value:0};class Ya{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await Bo(t);else if("string"==typeof t){let e=await B(t,"blob");a=await Bo(e)}else A(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return o&&(new Wa).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}}class Ha{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await Bo(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await Bo(t);return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await Bo(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}}!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(ca||(ca={}));class Xa{constructor(t){if(ua.add(this),ga.set(this,void 0),ma.set(this,{status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]}),pa.set(this,!1),_a.set(this,void 0),va.set(this,void 0),ya.set(this,void 0),wa.set(this,void 0),this.config=po(Xt),t&&"object"!=typeof t||Array.isArray(t))throw"Invalid config.";go(this.config,t),Ds._isRTU=!0}get disposed(){return e(this,pa,"f")}launch(){return t(this,void 0,void 0,function*(){if(e(this,pa,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(e(Xa,da,"f",fa)&&!e(Xa,da,"f",fa).isFulfilled&&!e(Xa,da,"f",fa).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return i(Xa,da,new Kt,"f",fa),e(this,ua,"m",Ca).call(this),e(Xa,da,"f",fa)})}decode(n,r="ReadBarcodes_Default"){return t(this,void 0,void 0,function*(){i(this,va,r,"f"),yield e(this,ua,"m",Ea).call(this,!0),e(this,wa,"f")||i(this,wa,new oa,"f"),e(this,wa,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(e(this,wa,"f"));const t=new Ye;t.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(t);const s=yield this._cvRouter.capture(n,r);return e(this,wa,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(e(this,wa,"f")),this._cvRouter.removeResultReceiver(t),s})}dispose(){var t,n,r,s,o,a,h;i(this,pa,!0,"f"),e(Xa,da,"f",fa)&&e(Xa,da,"f",fa).isPending&&e(Xa,da,"f",fa).resolve(e(this,ma,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(n=this._cameraView)||void 0===n||n.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",e(this,ga,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}da=Xa,ga=new WeakMap,ma=new WeakMap,pa=new WeakMap,_a=new WeakMap,va=new WeakMap,ya=new WeakMap,wa=new WeakMap,ua=new WeakSet,Ca=function(){return t(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield e(this,ua,"m",Ea).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),mo(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){e(this,ua,"m",ja).call(this,document.querySelector(".btn-upload-image"),!0),e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,va,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(t){e(this,ma,"f").status={code:l.RS_FAILED,message:t.message||t},e(Xa,da,"f",fa).reject(new Error(e(this,ma,"f").status.message)),this.dispose()}finally{e(this,ua,"m",Va).call(this,"Loading...",!1)}})},Ea=function(n=!1){return t(this,void 0,void 0,function*(){if(Ht.engineResourcePaths=this.config.engineResourcePaths,!n){const t=V(Ht.engineResourcePaths);if(this._cameraView=yield Br.createInstance(t.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this._cameraView._createDrawingLayer(2),this.config.scanMode===a.SM_SINGLE||this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1)}if(this._cameraEnhancer=yield Ds.createInstance(this._cameraView),this.disposed)return;if(yield e(this,ua,"m",ba).call(this),this.disposed)return;this.config.scannerViewConfig.customHighlightForBarcode&&i(this,ya,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}yield ho.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield We.createInstance()),this.disposed||(this.config.scanMode!==a.SM_SINGLE||n?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{e(Xa,da,"f",fa).reject(new Error(t.message)),this.dispose()},yield e(this,ua,"m",Sa).call(this,n),this.disposed||n||(this._cvRouter.setInput(this._cameraEnhancer),e(this,ua,"m",La).call(this),yield e(this,ua,"m",Ma).call(this),this.disposed)))})},Sa=function(n=!1){return t(this,void 0,void 0,function*(){if(n||(this.config.scanMode===a.SM_SINGLE?i(this,va,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===a.SM_MULTI_UNIQUE&&i(this,va,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const t=yield this._cvRouter.getSimplifiedSettings(e(this,va,"f"));if(this.disposed)return;n||this.config.scanMode!==a.SM_SINGLE||(t.outputOriginalImage=!0);let r=this.config.barcodeFormats;if(r){Array.isArray(r)||(r=[r]),t.barcodeSettings.barcodeFormatIds=BigInt(0);for(let e=0;e{document.head.appendChild(t.cloneNode(!0))}),this.config.scanMode===a.SM_SINGLE){const t=document.createElement("style");t.innerText="@keyframes result-option-flash {\n from {transform: translate(-50%, -50%) scale(1);}\n to {transform: translate(-50%, -50%) scale(0.8);}\n }";this._cameraView.getUIElement().shadowRoot.append(t)}i(this,_a,s.querySelector(".result-item"),"f"),e(this,ua,"m",Ta).call(this,s),e(this,ua,"m",Ia).call(this,s),e(this,ua,"m",xa).call(this,s),e(this,ua,"m",Oa).call(this,s),yield e(this,ua,"m",Ra).call(this,s),e(this,ua,"m",ja).call(this,s.querySelector(".btn-upload-image"),this.config.showUploadImageButton),e(this,ua,"m",Da).call(this,s),e(this,ua,"m",Aa).call(this,s)})},Ta=function(t){var i,n,r;const s=t.querySelector(".btn-clear");if(s&&(s.addEventListener("click",()=>{e(this,ma,"f").barcodeResults=[],e(this,ua,"m",Na).call(this)}),null===(r=null===(n=null===(i=this.config)||void 0===i?void 0:i.resultViewConfig)||void 0===n?void 0:n.toolbarButtonsConfig)||void 0===r?void 0:r.clear)){const e=this.config.resultViewConfig.toolbarButtonsConfig.clear;s.style.display=e.isHidden?"none":"flex",s.className=e.className?e.className:"btn-clear",s.innerText=e.label?e.label:"Clear",e.isHidden&&(t.querySelector(".toolbar-btns").style.justifyContent="center")}},Ia=function(t){var e,i,n;const r=t.querySelector(".btn-done");if(r&&(r.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(n=null===(i=null===(e=this.config)||void 0===e?void 0:e.resultViewConfig)||void 0===i?void 0:i.toolbarButtonsConfig)||void 0===n?void 0:n.done)){const e=this.config.resultViewConfig.toolbarButtonsConfig.done;r.style.display=e.isHidden?"none":"flex",r.className=e.className?e.className:"btn-done",r.innerText=e.label?e.label:"Done",e.isHidden&&(t.querySelector(".toolbar-btns").style.justifyContent="center")}},xa=function(t){var i,n;if(null===(n=null===(i=this.config)||void 0===i?void 0:i.scannerViewConfig)||void 0===n?void 0:n.showCloseButton){const i=t.querySelector(".btn-close");i&&(i.style.display="",i.addEventListener("click",()=>{e(this,ma,"f").barcodeResults=[],e(this,ma,"f").status={code:l.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}},Oa=function(i){var n;if(null===(n=this.config)||void 0===n?void 0:n.scannerViewConfig.showFlashButton){const n=i.querySelector(".btn-flash-auto"),r=i.querySelector(".btn-flash-open"),s=i.querySelector(".btn-flash-close");if(n){n.style.display="";let i=null,o=250,a=20,h=3;const l=(l=250)=>t(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==i){if(!(lt(this,void 0,void 0,function*(){var t;if(e(this,pa,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(i),void(i=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(i),i=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(_.IPF_GRAYSCALED===l.format){for(let t=0;t=h){null===(t=Ds._onLog)||void 0===t||t.call(Ds,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,n.style.display="none",r.style.display="",s.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});i=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),n.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),n.style.display="none",r.style.display="",s.style.display="none"})),r.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),n.style.display="none",r.style.display="none",s.style.display=""})),s.addEventListener("click",()=>t(this,void 0,void 0,function*(){l(1e3),n.style.display="",r.style.display="none",s.style.display="none"}))}}},Ra=function(i){return t(this,void 0,void 0,function*(){let n=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(n)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const n=i.querySelector(".camera-control");if(n){n.style.display="";const r=yield this._cameraEnhancer.getAllCameras(),s=this.config.scannerViewConfig.cameraSwitchControl,o=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px",cursor:"pointer"}),e},a=()=>{if(0===r.length)return null;if("listAll"===s){const n=i.querySelector(".camera-list");for(let t of r){const e=o(t);n.append(e)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const s=t=>{for(let e of a)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};n.addEventListener("click",i=>t(this,void 0,void 0,function*(){const t=i.target;e(this,ua,"m",Va).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:t.deviceId,label:t.label,_checked:t._checked});const n=this._cameraEnhancer.getSelectedCamera(),r=this._cameraEnhancer.getCapabilities();mo(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(r.torch?e(this,ua,"m",Ua).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),s(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,va,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),e(this,ua,"m",Va).call(this,"Loading...",!1)}));const a=i.querySelectorAll(".camera-list div");return()=>t(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();s(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===s?()=>t(this,void 0,void 0,function*(){e(this,ua,"m",Va).call(this,"Accessing Camera...",!0);const t=mo(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&e(this,ua,"m",Ua).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),e(this,ua,"m",Va).call(this,"Loading...",!1)}):void 0},h=a();n.addEventListener("click",e=>t(this,void 0,void 0,function*(){e.stopPropagation(),h&&(yield h())}))}}})},Aa=function(t){const n=this._cameraView.getUIElement();n.shadowRoot.querySelector(".dce-sel-camera").remove(),n.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const r=t.querySelector(".barcode-scanner-container");r.style.display=uo()?"flex":"",this.config.scanMode===a.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===a.SM_SINGLE&&(this.config.showResultView=!1);const s=this.config.showResultView;let o;if(this.config.container?(r.style.position="relative",o=this.config.container):o=document.body,"string"==typeof o&&(o=document.querySelector(o),null===o))throw new Error("Failed to get the container");let h=this.config.scannerViewConfig.container;if("string"==typeof h&&(h=document.querySelector(h),null===h))throw new Error("Failed to get the container of the scanner view.");let l=this.config.resultViewConfig.container;if("string"==typeof l&&(l=document.querySelector(l),null===l))throw new Error("Failed to get the container of the result view.");const c=t.querySelector(".scanner-view-container"),u=t.querySelector(".result-view-container"),d=t.querySelector(".loading-page");c.append(d),h&&(c.append(n),h.append(c)),l&&l.append(u),h||l?h&&!l?(this.config.container||(u.style.position="absolute"),l=u,o.append(u)):!h&&l&&(this.config.container||(c.style.position="absolute"),h=c,c.append(n),o.append(c)):(h=c,l=u,s&&(Object.assign(c.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"}),Object.assign(u.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"})),c.append(n),o.append(r)),document.querySelector(".result-view-container").style.display=s?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),i(this,ga,()=>{Object.assign(r.style,{display:uo()?"flex":""}),!s||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(h.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"}),Object.assign(l.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"}))},"f"),window.addEventListener("resize",e(this,ga,"f"))},Da=function(i){i.querySelector(".resume").addEventListener("click",()=>t(this,void 0,void 0,function*(){document.querySelector(".features-group").style.display="flex",document.querySelector(".btn-close").style.display="block",document.querySelector(".resume").style.display="none",this._cameraView.getUIElement().shadowRoot.querySelector(".single-mode-mask").remove(),this._cameraView.getUIElement().shadowRoot.querySelectorAll(".single-barcode-result-option").forEach(t=>t.remove()),yield this._cameraEnhancer.resume(),yield new Promise(t=>{setTimeout(t,100)}),this._cvRouter.startCapturing(e(this,va,"f"))}))},La=function(){const i=new Ye;i.onCapturedResultReceived=i=>t(this,void 0,void 0,function*(){if(e(this,ya,"f")&&e(this,ya,"f").clearDrawingItems(),i.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of i.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));e(this,ya,"f").addDrawingItems(t)}this.config.scanMode===a.SM_SINGLE?e(this,ua,"m",Fa).call(this,i):e(this,ua,"m",Pa).call(this,i)}}),this._cvRouter.addResultReceiver(i)},Ma=function(){return t(this,void 0,void 0,function*(){e(this,wa,"f")||i(this,wa,new oa,"f"),e(this,wa,"f").enableResultCrossVerification(2,!0),e(this,wa,"f").enableResultDeduplication(2,!0),e(this,wa,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(e(this,wa,"f")),e(this,wa,"f").isResultCrossVerificationEnabled=()=>!1,e(this,wa,"f").isResultDeduplicationEnabled=()=>!1})},Fa=function(t){const i=this._cameraView.getUIElement().shadowRoot;let n=new Promise(n=>{if(t.decodedBarcodesResult.barcodeResultItems.length>1){e(this,ua,"m",ka).call(this);let r=[];for(let e of t.decodedBarcodesResult.barcodeResultItems){let t=0,i=0;for(let n=0;n<4;++n){let r=e.location.points[n];t+=r.x,i+=r.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:t/4,y:i/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px",transform:"translate(-50%, -50%)",animation:"1s infinite alternate result-option-flash","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{n(e)}),r.push(o)}i.append(...r)}else n(t.decodedBarcodesResult.barcodeResultItems[0])});n.then(i=>{const n=t.items.filter(t=>t.type===ft.CRIT_ORIGINAL_IMAGE)[0].imageData,r={status:{code:l.RS_SUCCESS,message:"Success."},originalImageResult:n,barcodeImage:(()=>{const t=W(n),e=i.location.points,r=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-r,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-r,e[0].y-s);for(let t=1;t`${t.formatString}_${t.text}`==`${i.formatString}_${i.text}`);-1===t?(i.count=1,e(this,ma,"f").barcodeResults.unshift(i),e(this,ua,"m",Na).call(this,i)):(e(this,ma,"f").barcodeResults[t].count++,e(this,ua,"m",Ba).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},ka=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0",opacity:"0.5","background-color":"#4C4C4C"}),t.append(e),document.querySelector(".features-group").style.display="none",document.querySelector(".btn-close").style.display="none",document.querySelector(".resume").style.display="block",this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Na=function(t){if(!this.config.showResultView)return;const i=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==a.SM_SINGLE))return;const n=document.querySelector(".main-list");if(!t)return n.textContent="",void(this.config.showPoweredByDynamsoft&&(i.style.display=""));i.style.display="none";const r=(t=>{const i=e(this,_a,"f").cloneNode(!0);i.querySelector(".format-string").innerText=t.formatString;i.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),i.id=`${t.formatString}_${t.text}`;return i.querySelector(".delete-icon").addEventListener("click",()=>{const i=[...document.querySelectorAll(".main-list .result-item")],n=i.findIndex(e=>e.id===`${t.formatString}_${t.text}`);e(this,ma,"f").barcodeResults.splice(n,1),i[n].remove(),0===e(this,ma,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),i})(t);n.insertBefore(r,document.querySelector(".result-item"))},Ba=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},ja=function(i,n){n&&(i.style.display="",i.onchange=i=>t(this,void 0,void 0,function*(){const t=i.target.files,n={status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]};let r=0;e(this,ua,"m",Va).call(this,`Capturing... [${r}/${t.length}]`,!0);let s=!1;for(let e=0;e`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===i?(t.count=1,e(this,ma,"f").barcodeResults.unshift(t),e(this,ua,"m",Na).call(this,t)):(e(this,ma,"f").barcodeResults[i].count++,e(this,ua,"m",Ba).call(this,i))}else if(s.decodedBarcodesResult.barcodeResultItems)for(let t of s.decodedBarcodesResult.barcodeResultItems){const e=n.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,n.barcodeResults.push(t))}e(this,ua,"m",Va).call(this,`Capturing... [${++r}/${t.length}]`,!0)}catch(t){n.status={code:l.RS_FAILED,message:t.message||t},e(Xa,da,"f",fa).reject(new Error(n.status.message)),this.dispose()}e(this,ua,"m",Va).call(this,"Loading...",!1),this.config.scanMode===a.SM_SINGLE&&(e(Xa,da,"f",fa).resolve(n),this.dispose()),i.target.value=""}))},Ua=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},Va=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},Ga=function(t){let e=Ft();Pt[e]=()=>{},Lt.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},fa={value:null};const za="undefined"==typeof self,qa="function"==typeof importScripts,Ka=(()=>{if(!qa){if(!za&&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"./"}})(),Za=t=>{if(null==t&&(t="./"),za||qa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Ht.engineResourcePaths.dbr={version:"11.2.20-dev-20251029130556",path:Ka,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const Ja="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,Ja)<0&&(Ht.engineResourcePaths.std={version:Ja,path:Za(Ka+`../../dynamsoft-capture-vision-std@${Ja}/dist/`),isInternal:!0});const $a="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,$a)<0)&&(Ht.engineResourcePaths.dip={version:$a,path:Za(Ka+`../../dynamsoft-image-processing@${$a}/dist/`),isInternal:!0});let Qa=class{static getVersion(){const t=Ut.dbr&&Ut.dbr.wasm;return`11.2.20-dev-20251029130556(Worker: ${Ut.dbr&&Ut.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const th={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var eh,ih,nh,rh,sh,oh;function ah(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:hh(e,t,"map"),t.getFieldRawValue=t=>hh(e,t,"raw"),t.getFieldMappingStatus=t=>lh(e,t),t.getFieldValidationStatus=t=>ch(e,t),delete t.fullCodeString}function hh(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=hh(r,e,i);if(void 0!==t)return t}}}function lh(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(sh[i.MappingStatus]):sh.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=lh(n,e);if(void 0!==t)return t}}}function ch(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(oh[i.ValidationStatus]):oh.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=ch(n,e);if(void 0!==t)return t}}}function uh(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!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"}(eh||(eh={})),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"}(ih||(ih={})),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_NEURAL_NETWORK=512]="LM_NEURAL_NETWORK",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(nh||(nh={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(rh||(rh={})),function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(sh||(sh={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(oh||(oh={}));const dh=t=>t&&"object"==typeof t&&"function"==typeof t.then,fh=(async()=>{})().constructor;class gh extends fh{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,dh(t)?e=t:"function"==typeof t&&(e=new fh(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(dh(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class mh{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!Vt.license)throw Error("Module `license` is not existed.");await Vt.license.dynamsoft(),await Ht.loadWasm();const t=new mh,e=new gh;let i=Ft();return Pt[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},Lt.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){uh(this);let t=Ft();this.bDestroyed=!0,Pt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Lt.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(uh(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await B(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return uh(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(uh(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise((i,n)=>{let r=Ft();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(ah(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Lt.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const ph="undefined"==typeof self,_h="function"==typeof importScripts,vh=(()=>{if(!_h){if(!ph&&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"./"}})();Ht.engineResourcePaths.dcp={version:"3.2.20-dev-20251029130614",path:vh,isInternal:!0},Gt.dcp={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE]},Vt.dcp={handleParsedResultItem:ah};const yh="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,yh)<0&&(Ht.engineResourcePaths.std={version:yh,path:(t=>{if(null==t&&(t="./"),ph||_h);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(vh+`../../dynamsoft-capture-vision-std@${yh}/dist/`),isInternal:!0}),Pt[-4]=async t=>{wh.onSpecLoadProgressChanged&&wh.onSpecLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class wh{static getVersion(){const t=Ut.dcp&&Ut.dcp.wasm;return`3.2.20-dev-20251029130614(Worker: ${Ut.dcp&&Ut.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await Ht.loadWasm(),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],o=V(Ht.engineResourcePaths);Lt.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===Ht._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}}Ht._bundleEnv="DBR",We._defaultTemplate="ReadSingleBarcode",Ht.engineResourcePaths.rootDirectory=o(s+"../../"),Ht.engineResourcePaths.dbrBundle={version:"11.2.2000",path:s,isInternal:!0};export{Qa as BarcodeReaderModule,Xa as BarcodeScanner,Ds as CameraEnhancer,ei as CameraEnhancerModule,Vr as CameraManager,Br as CameraView,We as CaptureVisionRouter,fe as CaptureVisionRouterModule,Ye as CapturedResultReceiver,mh as CodeParser,wh as CodeParserModule,Ht as CoreModule,Ai as DrawingItem,Lr as DrawingStyleManager,th as EnumBarcodeFormat,m as EnumBufferOverflowProtectionMode,ft as EnumCapturedResultItemType,p as EnumColourChannelUsageType,gt as EnumCornerType,Ct as EnumCrossVerificationStatus,rh as EnumDeblurMode,di as EnumDrawingItemMediaType,fi as EnumDrawingItemState,gi as EnumEnhancedFeatures,mt as EnumErrorCode,eh as EnumExtendedBarcodeResultType,ca as EnumFilterType,pt as EnumGrayscaleEnhancementMode,_t as EnumGrayscaleTransformationMode,It as EnumImageCaptureDistanceMode,Tt as EnumImageFileFormat,_ as EnumImagePixelFormat,ge as EnumImageSourceState,vt as EnumImageTagType,Et as EnumIntermediateResultUnitType,nh as EnumLocalizationMode,sh as EnumMappingStatus,xt as EnumModuleName,h as EnumOptimizationMode,yt as EnumPDFReadingMode,Xe as EnumPresetTemplate,ih as EnumQRCodeErrorCorrectionLevel,wt as EnumRasterDataSource,St as EnumRegionObjectElementType,l as EnumResultStatus,a as EnumScanMode,bt as EnumSectionType,Ot as EnumTransformMatrixType,oh as EnumValidationStatus,Ts as Feedback,Yi as GroupDrawingItem,jr as ImageDataGetter,Ya as ImageDrawer,Ni as ImageDrawingItem,Vs as ImageEditorView,Wa as ImageIO,Ha as ImageProcessor,ht as ImageSourceAdapter,He as IntermediateResultReceiver,ho as LicenseManager,co as LicenseModule,Gi as LineDrawingItem,oa as MultiFrameResultCrossFilter,Wi as QuadDrawingItem,Di as RectDrawingItem,ji as TextDrawingItem,bo as UtilityModule,X as _getNorImageData,G as _saveToFile,H as _toBlob,W as _toCanvas,Y as _toImage,Bt as bDebug,j as checkIsLink,U as compareVersion,Dt as doOrWaitAsyncDependency,Ft as getNextTaskID,V as handleEngineResourcePaths,Ut as innerVersions,I as isArc,x as isContour,A as isDSImageData,D as isDSRect,L as isImageTag,M as isLineSegment,T as isObject,R as isOriginalDsImageData,F as isPoint,P as isPolygon,k as isQuad,N as isRect,z as isSimdSupported,Rt as mapAsyncDependency,Vt as mapPackageRegister,Pt as mapTaskCallBack,kt as onLog,q as productNameMap,B as requestResource,jt as setBDebug,Nt as setOnLog,At as waitAsyncDependency,Lt as worker,Gt as workerAutoResources}; diff --git a/dist/dbr.bundle.js b/dist/dbr.bundle.js index ed436ab..e7eb8ea 100644 --- a/dist/dbr.bundle.js +++ b/dist/dbr.bundle.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 11.0.6000 +* @version 11.2.2000 * @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=t.Dynamsoft||{})}(this,function(t){"use strict";function e(t,e,i,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function i(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function n(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const r="undefined"==typeof self,s="function"==typeof importScripts,o=(()=>{if(!s){if(!r&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),a=t=>{if(null==t&&(t="./"),r||s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var h,l,c;t.EnumScanMode=void 0,(h=t.EnumScanMode||(t.EnumScanMode={}))[h.SM_SINGLE=0]="SM_SINGLE",h[h.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE",t.EnumOptimizationMode=void 0,(l=t.EnumOptimizationMode||(t.EnumOptimizationMode={}))[l.OM_NONE=0]="OM_NONE",l[l.OM_SPEED=1]="OM_SPEED",l[l.OM_COVERAGE=2]="OM_COVERAGE",l[l.OM_BALANCE=3]="OM_BALANCE",l[l.OM_DPM=4]="OM_DPM",l[l.OM_DENSE=5]="OM_DENSE",t.EnumResultStatus=void 0,(c=t.EnumResultStatus||(t.EnumResultStatus={}))[c.RS_SUCCESS=0]="RS_SUCCESS",c[c.RS_CANCELLED=1]="RS_CANCELLED",c[c.RS_FAILED=2]="RS_FAILED";const u=t=>t&&"object"==typeof t&&"function"==typeof t.then,d=(async()=>{})().constructor;let f=class extends d{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,u(t)?e=t:"function"==typeof t&&(e=new d(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(u(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function g(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function m(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var p,_,v;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(p||(p={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(_||(_={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(v||(v={}));const y="undefined"==typeof self,w="function"==typeof importScripts,E=(()=>{if(!w){if(!y&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),C=t=>{if(null==t&&(t="./"),y||w);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},S=t=>Object.prototype.toString.call(t),b=t=>Array.isArray?Array.isArray(t):"[object Array]"===S(t),T=t=>"number"==typeof t&&!Number.isNaN(t),I=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),x=t=>!(!I(t)||!T(t.width)||t.width<=0||!T(t.height)||t.height<=0||!T(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!A(t.tag)),O=t=>!!x(t)&&t.bytes instanceof Uint8Array,R=t=>!(!I(t)||!T(t.left)||t.left<0||!T(t.top)||t.top<0||!T(t.right)||t.right<0||!T(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),A=t=>null===t||!!I(t)&&!!T(t.imageId)&&"type"in t,D=t=>!(!I(t)||!L(t.startPoint)||!L(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),L=t=>!!I(t)&&!!T(t.x)&&!!T(t.y),M=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),F=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!L(t)),P=t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.width)||t.width<0||!T(t.height)||t.height<0),k=async(t,e)=>await new Promise((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}),N=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${W[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${W[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},j=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await V(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),U=t=>{O(t)&&(t=G(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},V=async(t,e)=>{O(e)&&(e=G(e));const i=U(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},G=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===v.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===v.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},W={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var Y,H,X,z,q,K,Z,J;let $,Q,tt,et,it,nt=class t{get _isFetchingStarted(){return g(this,q,"f")}constructor(){Y.add(this),H.set(this,[]),X.set(this,1),z.set(this,p.BOPM_BLOCK),q.set(this,!1),K.set(this,void 0),Z.set(this,_.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!O(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(g(this,H,"f").length>=g(this,X,"f"))switch(g(this,z,"f")){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:if(g(this,H,"f").push(t),I(g(this,K,"f"))&&T(g(this,K,"f").imageId)&&1==g(this,K,"f").keepInBuffer)for(;g(this,H,"f").length>g(this,X,"f");){const t=g(this,H,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==g(this,K,"f").imageId});g(this,H,"f").splice(t,1)}else g(this,H,"f").splice(0,g(this,H,"f").length-g(this,X,"f"))}else g(this,H,"f").push(t)}getImage(){if(0===g(this,H,"f").length)return null;let e;if(g(this,K,"f")&&T(g(this,K,"f").imageId)){const t=g(this,Y,"m",J).call(this,g(this,K,"f").imageId);if(t<0)throw new Error(`Image with id ${g(this,K,"f").imageId} doesn't exist.`);e=g(this,H,"f").slice(t,t+1)[0]}else e=g(this,H,"f").pop();if([v.IPF_RGB_565,v.IPF_RGB_555,v.IPF_RGB_888,v.IPF_ARGB_8888,v.IPF_RGB_161616,v.IPF_ARGB_16161616,v.IPF_ABGR_8888,v.IPF_ABGR_16161616,v.IPF_BGR_888].includes(e.format)){if(g(this,Z,"f")===_.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every(t=>T(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==S(e))throw new TypeError("Invalid 'keepInBuffer'.");m(this,K,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){m(this,K,null,"f")}hasImage(t){return g(this,Y,"m",J).call(this,t)>=0}startFetching(){m(this,q,!0,"f")}stopFetching(){m(this,q,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(m(this,X,t,"f");g(this,H,"f")&&g(this,H,"f").length>t;)g(this,H,"f").shift()}getMaxImageCount(){return g(this,X,"f")}getImageCount(){return g(this,H,"f").length}clearBuffer(){g(this,H,"f").length=0}isBufferEmpty(){return 0===g(this,H,"f").length}setBufferOverflowProtectionMode(t){m(this,z,t,"f")}getBufferOverflowProtectionMode(){return g(this,z,"f")}setColourChannelUsageType(t){m(this,Z,t,"f")}getColourChannelUsageType(){return g(this,Z,"f")}};H=new WeakMap,X=new WeakMap,z=new WeakMap,q=new WeakMap,K=new WeakMap,Z=new WeakMap,Y=new WeakSet,J=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return g(this,H,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&($=navigator,Q=$.userAgent,tt=$.platform,et=$.mediaDevices),function(){if(!y){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:$.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:tt,search:"Win"},Mac:{str:tt},Linux:{str:tt}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Q,o=r.search||e,a=r.verStr||Q,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Q,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Q.indexOf("Windows NT")&&(r="HarmonyOS"),it={browser:i,version:n,OS:r}}y&&(it={browser:"ssr",version:0,OS:"ssr"})}();const rt="undefined"!=typeof WebAssembly&&Q&&!(/Safari/.test(Q)&&!/Chrome/.test(Q)&&/\(.+\s11_2_([2-6]).*\)/.test(Q)),st=!("undefined"==typeof Worker),ot=!(!et||!et.getUserMedia),at=async()=>{let t=!1;if(ot)try{(await et.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var ht,lt,ct,ut,dt,ft,gt,mt,pt;"Chrome"===it.browser&&it.version>66||"Safari"===it.browser&&it.version>13||"OPR"===it.browser&&it.version>43||"Edge"===it.browser&&it.version,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(ht||(ht={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(lt||(lt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(ct||(ct={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV",t[t.GEM_END=-1]="GEM_END"}(ut||(ut={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV",t[t.GTM_END=-1]="GTM_END"}(dt||(dt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(ft||(ft={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(gt||(gt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(mt||(mt={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(pt||(pt={}));const _t={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var vt,yt,wt,Et,Ct,St;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(vt||(vt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(yt||(yt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(wt||(wt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(Et||(Et={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(Ct||(Ct={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(St||(St={}));const bt={},Tt=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(bt[t]=bt[t]||new f);await Promise.all(i)},It=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=bt[t]=bt[t]||new f(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let xt,Ot=0;const Rt=()=>Ot++,At={};let Dt;const Lt=t=>{Dt=t,xt&&xt.postMessage({type:"setBLog",body:{value:!!t}})};let Mt=!1;const Ft=t=>{Mt=t,xt&&xt.postMessage({type:"setBDebug",body:{value:!!t}})},Pt={},kt={},Nt={dip:{wasm:!0}},Bt={std:{version:"2.0.0",path:C(E+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.0.60-dev-20250812165815",path:E,isInternal:!0}};class jt{static get engineResourcePaths(){return Bt}static set engineResourcePaths(t){Object.assign(Bt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return Dt}static set _onLog(t){Lt(t)}static get _bDebug(){return Mt}static set _bDebug(t){Ft(t)}static get _workerName(){return`${jt._bundleEnv.toLowerCase()}.bundle.worker.js`}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!bt[t]&&bt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=bt.core;e=!i||i.isEmpty,e||await Tt("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),Ct.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||Ct.MN_DYNAMSOFT_CORE==t)return;let e=Nt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=bt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await It(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await Tt(o);const i=B(Bt),r={};for(let e of t)r[e]=Nt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:jt._bundleEnv,_useSimd:jt._useSimd,_useMLBackend:jt._useMLBackend};let a=new f;if(e){s.needLoadCore=!0;let t=i[`${jt._bundleEnv.toLowerCase()}Bundle`]+jt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),xt=new Worker(t),xt.onerror=t=>{let e=new Error(t.message);a.reject(e)},xt.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":Dt&&Dt(e.message);break;case"task":try{At[n](r),delete At[n]}catch(t){throw delete At[n],t}break;case"event":try{At[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!Dt,s.bd=Mt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await Tt("core");let h=Ot++;At[h]=t=>{if(t.success)Object.assign(Pt,t.versions),"{}"!==JSON.stringify(t.versions)&&(jt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},xt.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:rt,worker:st,getUserMedia:ot,camera:await at(),browser:it.browser,version:it.version,OS:it.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.0.60-dev-20250812165815(Worker: ${Pt.core&&Pt.core.worker||"Not Loaded"}, Wasm: ${Pt.core&&Pt.core.wasm||"Not Loaded"})`}static enableLogging(){nt._onLog=console.log,jt._onLog=console.log}static disableLogging(){nt._onLog=null,jt._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"cfd",id:n,body:{count:t}})})}}jt._bSupportDce4Module=-1,jt._bSupportIRTModule=-1,jt._versions=null,jt._bundleEnv="DCV",jt._useMLBackend=!1,jt._useSimd=!0,jt.browserInfo=it;var Ut=Object.freeze({__proto__:null,CoreModule:jt,get EnumBufferOverflowProtectionMode(){return p},get EnumCapturedResultItemType(){return ht},get EnumColourChannelUsageType(){return _},get EnumCornerType(){return lt},get EnumCrossVerificationStatus(){return pt},get EnumErrorCode(){return ct},get EnumGrayscaleEnhancementMode(){return ut},get EnumGrayscaleTransformationMode(){return dt},get EnumImageCaptureDistanceMode(){return Et},get EnumImageFileFormat(){return wt},get EnumImagePixelFormat(){return v},get EnumImageTagType(){return ft},EnumIntermediateResultUnitType:_t,get EnumModuleName(){return Ct},get EnumPDFReadingMode(){return gt},get EnumRasterDataSource(){return mt},get EnumRegionObjectElementType(){return vt},get EnumSectionType(){return yt},get EnumTransformMatrixType(){return St},ImageSourceAdapter:nt,_getNorImageData:G,_saveToFile:j,_toBlob:V,_toCanvas:U,_toImage:(t,e)=>{O(e)&&(e=G(e));const i=U(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},get bDebug(){return Mt},checkIsLink:t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),compareVersion:N,doOrWaitAsyncDependency:It,getNextTaskID:Rt,handleEngineResourcePaths:B,innerVersions:Pt,isArc:t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.radius)||t.radius<0||!T(t.startAngle)||!T(t.endAngle)),isContour:t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),isDSImageData:O,isDSRect:R,isImageTag:A,isLineSegment:D,isObject:I,isOriginalDsImageData:t=>!(!x(t)||!T(t.bytes.length)&&!T(t.bytes.ptr)),isPoint:L,isPolygon:M,isQuad:F,isRect:P,isSimdSupported:async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),mapAsyncDependency:bt,mapPackageRegister:kt,mapTaskCallBack:At,get onLog(){return Dt},productNameMap:W,requestResource:k,setBDebug:Ft,setOnLog:Lt,waitAsyncDependency:Tt,get worker(){return xt},workerAutoResources:Nt}),Vt={license:"",scanMode:t.EnumScanMode.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:jt.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:o,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Gt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Wt=(async()=>{})().constructor;class Yt extends Wt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Gt(t)?e=t:"function"==typeof t&&(e=new Wt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Gt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Ht(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Xt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const zt=t=>t&&"object"==typeof t&&"function"==typeof t.then,qt=(async()=>{})().constructor;let Kt=class extends qt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,zt(t)?e=t:"function"==typeof t&&(e=new qt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(zt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},Zt=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var Jt={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1,onProcessedDocumentResultReceived:!1};const $t=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};let Qt=class{constructor(t){this._irrRegistryState=Jt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),$t(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach((t,e)=>{i[e]=t}),t._observedTaskMap.clear()}return await new Promise((t,n)=>{let r=Rt();At[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},xt.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),$t(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const te="undefined"==typeof self,ee="function"==typeof importScripts,ie=(()=>{if(!ee){if(!te&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),ne=t=>{if(null==t&&(t="./"),te||ee);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var re;jt.engineResourcePaths.cvr={version:"3.0.60-dev-20250812165839",path:ie,isInternal:!0},Nt.cvr={js:!0,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING,Ct.MN_DYNAMSOFT_NEURAL_NETWORK]},Nt.dnn={wasm:!0,deps:[Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},kt.cvr={};const se="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,se)<0&&(jt.engineResourcePaths.std={version:se,path:ne(ie+`../../dynamsoft-capture-vision-std@${se}/dist/`),isInternal:!0});const oe="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,oe)<0)&&(jt.engineResourcePaths.dip={version:oe,path:ne(ie+`../../dynamsoft-image-processing@${oe}/dist/`),isInternal:!0});const ae="2.0.10";(!jt.engineResourcePaths.dnn||"string"!=typeof jt.engineResourcePaths.dnn&&N(jt.engineResourcePaths.dnn.version,ae)<0)&&(jt.engineResourcePaths.dnn={version:ae,path:ne(ie+`../../dynamsoft-capture-vision-dnn@${ae}/dist/`),isInternal:!0});let he=class{static getVersion(){return this._version}};var le,ce,ue,de,fe,ge,me,pe,_e,ve,ye,we,Ee,Ce,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le;function Me(t,e){if(t&&t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Me(t.referencedItem,e)}}function Fe(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function Pe(t){let e=!1;const i=[ct.EC_UNSUPPORTED_JSON_KEY_WARNING,ct.EC_LICENSE_AUTH_QUOTA_EXCEEDED,ct.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}he._version=`3.0.60-dev-20250812165839(Worker: ${null===(re=Pt.cvr)||void 0===re?void 0:re.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(le||(le={}));const ke={onTaskResultsReceived:()=>{},isFilter:!0};At[-2]=async t=>{Ne.onDataLoadProgressChanged&&Ne.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let Ne=class t{constructor(){ce.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(jt.browserInfo.OS)?2048:4096,this.onCaptureError=null,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._dynamsoft=!0,ue.set(this,null),de.set(this,null),fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,new Set),_e.set(this,new Set),ve.set(this,new Set),ye.set(this,500),we.set(this,0),Ee.set(this,0),Ce.set(this,!1),Se.set(this,!1),be.set(this,!1),Te.set(this,null),Ie.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Ht(this,be,"f")}static async createInstance(e=!0){if(!kt.license)throw Error("The `license` module cannot be found.");await kt.license.dynamsoft(),await jt.loadWasm();const i=new t,n=new Kt;let r=Rt();return At[r]=async t=>{t.success?(i._instanceID=t.instanceID,i._currentSettings=JSON.parse(JSON.parse(t.outputSettings).data),he._version=`3.0.60-dev-20250812165839(Worker: ${Pt.cvr.worker}, Wasm: ${t.version})`,Xt(i,Se,!0,"f"),Xt(i,ge,i.getIntermediateResultManager(),"f"),Xt(i,Se,!1,"f"),n.resolve(i)):Pe({message:t.message,rj:n.reject,stack:t.stack,functionName:"createInstance"})},xt.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendModelBuffer(t,e){return await jt.loadWasm(),await new Promise((i,n)=>{let r=Rt();const s=B(jt.engineResourcePaths);let o;At[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Pe({message:e.errorString?e.errorString:"Append Model Buffer Failed.",rj:n,errorCode:e.errorCode,functionName:"appendModelBuffer"}),i(e)}Pe({message:t.message,rj:n,stack:t.stack,functionName:"appendModelBuffer"})},e?o=e:"DCV"===jt._bundleEnv?o=s.dcvData+"models/":"DBR"===jt._bundleEnv&&(o=s.dbrBundle+"models/"),xt.postMessage({type:"cvr_appendModelBuffer",id:r,body:{modelName:t,path:o}})})}async _singleFrameModeCallback(t){for(let e of Ht(this,pe,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of Ht(this,pe,"f"))t.isDce?t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}):Ht(this,ce,"m",Oe).call(this,t,i)}setInput(t){if(Fe(this),!t)return Ht(this,Te,"f")&&(Ht(this,ge,"f").removeResultReceiver(Ht(this,Te,"f")),Xt(this,Te,null,"f")),Ht(this,Ie,"f")&&(Ht(this,pe,"f").delete(Ht(this,Ie,"f")),Xt(this,Ie,null,"f")),void Xt(this,ue,null,"f");if(Xt(this,ue,t,"f"),t.isCameraEnhancer){Ht(this,ge,"f")&&(Ht(this,ue,"f")._intermediateResultReceiver.isDce=!0,Ht(this,ge,"f").addResultReceiver(Ht(this,ue,"f")._intermediateResultReceiver),Xt(this,Te,Ht(this,ue,"f")._intermediateResultReceiver,"f"));const t=Ht(this,ue,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Ht(this,pe,"f").add(e),Xt(this,Ie,e,"f")}}}getInput(){return Ht(this,ue,"f")}addImageSourceStateListener(t){if(Fe(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Ht(this,_e,"f").add(t)}removeImageSourceStateListener(t){return Fe(this),Ht(this,_e,"f").delete(t)}addResultReceiver(t){if(Fe(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Ht(this,pe,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Fe(this),Ht(this,pe,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Ht(this,pe,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Kt;let i=Rt();return At[i]=async t=>{t.success?e.resolve():Pe({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},xt.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Fe(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Ht(this,ve,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Fe(this),Ht(this,ve,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Ht(this,ge,"f").removeResultReceiver(ke),0===Ht(this,ve,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1},e={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1};return await Ht(this,ce,"m",Re).call(this,t),void await Ht(this,ce,"m",Ae).call(this,e)}for(let t of Ht(this,ve,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(ht.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(ht.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(ht.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(ht.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(ht.CRIT_BARCODE)&&([...Ht(this,ge,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Ht(this,ge,"f").addResultReceiver(ke)),await Ht(this,ce,"m",Re).call(this,t.verificationEnabled),await Ht(this,ce,"m",Ae).call(this,t.duplicateFilterEnabled),await Ht(this,ce,"m",De).call(this,t.duplicateForgetTime)}async startCapturing(e){if(Fe(this),!this._isPauseScan)return;if(!Ht(this,ue,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);const i=await this.containsTask(e);for(let t of Ht(this,ve,"f"))await this.addResultFilter(t);const n=B(jt.engineResourcePaths);return Ht(this,ue,"f").isCameraEnhancer&&(i.includes("ddn")?Ht(this,ue,"f").setPixelFormat(v.IPF_ABGR_8888):Ht(this,ue,"f").setPixelFormat(v.IPF_GRAYSCALED)),void 0!==Ht(this,ue,"f").singleFrameMode&&"disabled"!==Ht(this,ue,"f").singleFrameMode?(this._templateName=e,void Ht(this,ue,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(Ht(this,ue,"f").getColourChannelUsageType()===_.CCUT_AUTO&&Ht(this,ue,"f").setColourChannelUsageType(i.includes("ddn")?_.CCUT_FULL_CHANNEL:_.CCUT_Y_CHANNEL_ONLY),Ht(this,fe,"f")&&Ht(this,fe,"f").isPending?Ht(this,fe,"f"):(Xt(this,fe,new Kt((t,i)=>{if(this.disposed)return;let r=Rt();At[r]=async n=>{Ht(this,fe,"f")&&!Ht(this,fe,"f").isFulfilled&&(n.success?(this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Ht(this,ue,"f").startFetching(),this._loopReadVideo(e),t()},0)):Pe({message:n.message,rj:i,stack:n.stack,functionName:"startCapturing"}))},xt.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:n}})}),"f"),await Ht(this,fe,"f")))}stopCapturing(){Fe(this),Ht(this,ue,"f")&&(Ht(this,ue,"f").isCameraEnhancer&&void 0!==Ht(this,ue,"f").singleFrameMode&&"disabled"!==Ht(this,ue,"f").singleFrameMode?Ht(this,ue,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Ht(this,ce,"m",Le).call(this),Ht(this,ue,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Xt(this,fe,null,"f"),Ht(this,ue,"f").setColourChannelUsageType(_.CCUT_AUTO)))}async containsTask(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));Pe({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},xt.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Xt(this,Ce,!0,"f"),Ht(this,ue,"f").isBufferEmpty())if(Ht(this,ue,"f").hasNextImageToFetch())for(let t of Ht(this,_e,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(le.ISS_BUFFER_EMPTY);else if(!Ht(this,ue,"f").hasNextImageToFetch())for(let t of Ht(this,_e,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(le.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Ht(this,ue,"f").isBufferEmpty()&&Ht(this,ue,"f").isCameraEnhancer)try{Ht(this,ue,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Ht(this,ue,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Ht(this,ue,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Ht(this,ue,"f").isCameraEnhancer&&Ht(this,ue,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Ht(this,ue,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Ht(this,pe,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of Ht(this,pe,"f"))if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}else{for(let t of Ht(this,ve,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onProcessedDocumentResultReceived(n);Ht(this,ce,"m",Oe).call(this,e,n)}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Ht(this,ue,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Ht(this,ue,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async capture(e,i){let n;if(Fe(this),i||(i=t._defaultTemplate),Xt(this,Ce,!1,"f"),O(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await k(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Xt(this,Ee,this.maxImageSideLength/o,"f"),i=Math.round(r*Ht(this,Ee,"f")),n=Math.round(s*Ht(this,Ee,"f"))):(i=r,n=s),Ht(this,de,"f")||Xt(this,de,document.createElement("canvas"),"f");const a=Ht(this,de,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Xt(this,Ee,this.maxImageSideLength/o,"f"),i=Math.round(r*Ht(this,Ee,"f")),n=Math.round(s*Ht(this,Ee,"f"))):(i=r,n=s),Ht(this,de,"f")||Xt(this,de,document.createElement("canvas"),"f");const a=Ht(this,de,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Rt();B(jt.engineResourcePaths);const l=new Kt;return At[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;t.hasOwnProperty("_needContinueProcess")&&delete t._needContinueProcess,e.bytes=i.bytes;for(let i of t.items)0!==Ht(this,Ee,"f")&&Me(i,Ht(this,Ee,"f")),i.type===ht.CRIT_ORIGINAL_IMAGE?i.imageData=e:[ht.CRIT_DESKEWED_IMAGE,ht.CRIT_ENHANCED_IMAGE].includes(i.type)?kt.ddn&&kt.ddn.handleDeskewedAndEnhancedImageResultItem(i):i.type===ht.CRIT_PARSED_RESULT&&kt.dcp&&kt.dcp.handleParsedResultItem(i);const n=t.processedDocumentResult;if(n){if(n.deskewedImageResultItems)for(let t=0;tHt(this,ye,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),Xt(this,we,s,"f")),Xt(this,Ee,0,"f"),l.resolve(t)}catch(i){Pe({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else Pe({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),xt.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Ht(this,Ce,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(Fe(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await k(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Rt();At[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&Pe({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}Pe({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},xt.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return Fe(this),await new Promise((i,n)=>{let r=Rt();At[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Pe({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}Pe({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},xt.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,null,2,function(t,e){return e instanceof Array?JSON.stringify(e):e},2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return Fe(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Pe({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}Pe({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},xt.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return Fe(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&Pe({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}Pe({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},xt.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return Fe(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Rt();At[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&Pe({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}Pe({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},xt.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return Fe(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Pe({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}Pe({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},xt.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return Ht(this,me,"f")||Xt(this,me,new Zt(this),"f"),Ht(this,me,"f")}getIntermediateResultManager(){if(Fe(this),!Ht(this,Se,"f")&&0!==jt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Ht(this,ge,"f")||Xt(this,ge,new Qt(this),"f"),Ht(this,ge,"f")}async parseRequiredResources(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));Pe({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},xt.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){Fe(this),Ht(this,fe,"f")&&this.stopCapturing(),Xt(this,ue,null,"f"),Ht(this,pe,"f").clear(),Ht(this,_e,"f").clear(),Ht(this,ve,"f").clear(),Ht(this,ge,"f")._intermediateResultReceiverSet.clear(),Xt(this,be,!0,"f");let t=Rt();At[t]=t=>{t.success||Pe({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},xt.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Ht(this,ue,"f"),promiseStartScan:Ht(this,fe,"f"),intermediateResultManager:Ht(this,ge,"f"),bufferdItemsManager:Ht(this,me,"f"),resultReceiverSet:Ht(this,pe,"f"),isaStateListenerSet:Ht(this,_e,"f"),resultFilterSet:Ht(this,ve,"f"),compressRate:Ht(this,Ee,"f"),canvas:Ht(this,de,"f"),isScanner:Ht(this,Ce,"f"),innerUseTag:Ht(this,Se,"f"),isDestroyed:Ht(this,be,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}Pe({message:i.message,rj:e,stack:i.stack,functionName:""})},xt.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};ue=new WeakMap,de=new WeakMap,fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,ce=new WeakSet,xe=function(t,e){const i=t.intermediateResult;if(i){let t=0;for(let n of Ht(this,ge,"f")._intermediateResultReceiverSet){t++;for(let r of i){if(["onTaskResultsReceived","onTargetROIResultsReceived"].includes(r.info.callbackName)){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);t===Ht(this,ge,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}t&&t.hasOwnProperty("intermediateResult")&&delete t.intermediateResult},Oe=function(t,e){e.decodedBarcodesResult&&t.onDecodedBarcodesReceived&&t.onDecodedBarcodesReceived(e.decodedBarcodesResult),e.recognizedTextLinesResult&&t.onRecognizedTextLinesReceived&&t.onRecognizedTextLinesReceived(e.recognizedTextLinesResult),e.processedDocumentResult&&t.onProcessedDocumentResultReceived&&t.onProcessedDocumentResultReceived(e.processedDocumentResult),e.parsedResult&&t.onParsedResultsReceived&&t.onParsedResultsReceived(e.parsedResult),t.onCapturedResultReceived&&t.onCapturedResultReceived(e)},Re=async function(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(t.result);Pe({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},xt.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Ae=async function(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(t.result);Pe({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},xt.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},De=async function(t){return Fe(this),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return e(t.result);Pe({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},xt.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},Le=async function(){let t=Rt();const e=new Kt;return At[t]=async t=>{if(t.success)return e.resolve();Pe({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},xt.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},Ne._defaultTemplate="Default";let Be=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}};var je;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadSingleBarcode",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(je||(je={}));var Ue=Object.freeze({__proto__:null,CaptureVisionRouter:Ne,CaptureVisionRouterModule:he,CapturedResultReceiver:Be,get EnumImageSourceState(){return le},get EnumPresetTemplate(){return je},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=_t.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Ve="undefined"==typeof self,Ge="function"==typeof importScripts,We=(()=>{if(!Ge){if(!Ve&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();jt.engineResourcePaths.dce={version:"4.2.3-dev-20250812165927",path:We,isInternal:!0},Nt.dce={wasm:!1,js:!1},kt.dce={};let Ye,He,Xe,ze,qe;function Ke(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Ze(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ye=navigator,He=Ye.userAgent,Xe=Ye.platform,ze=Ye.mediaDevices),function(){if(!Ve){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ye.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Xe,search:"Win"},Mac:{str:Xe},Linux:{str:Xe}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||He,o=r.search||e,a=r.verStr||He,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||He,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=He.indexOf("Windows NT")&&(r="HarmonyOS"),qe={browser:i,version:n,OS:r}}Ve&&(qe={browser:"ssr",version:0,OS:"ssr"})}();const Je="undefined"!=typeof WebAssembly&&He&&!(/Safari/.test(He)&&!/Chrome/.test(He)&&/\(.+\s11_2_([2-6]).*\)/.test(He)),$e=!("undefined"==typeof Worker),Qe=!(!ze||!ze.getUserMedia),ti=async()=>{let t=!1;if(Qe)try{(await ze.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===qe.browser&&qe.version>66||"Safari"===qe.browser&&qe.version>13||"OPR"===qe.browser&&qe.version>43||"Edge"===qe.browser&&qe.version;var ei={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,E,C,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some(function(e){return"function"==typeof e.contains&&e.contains(t,!0)})},complexity:function(){return this._objects.reduce(function(t,e){return t+(e.complexity?e.complexity():0)},0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach(function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))}),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var S=Math.sqrt(1-E/(_*v));i*=S,s*=S}else C=(o===a?-1:1)*Math.sqrt(E/(_*y+v*w));var T=C*i*p/s,I=-C*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kC)for(var T=1,I=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var I,x,O,R=C.length,A=R;R--;)I=(O=1-(f=C[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(function(t){for(var i=t.slice(0),n={},r=1;r=e})}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach(function(t){t.cancel()}),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter(function(e){return"object"==typeof e.target&&e.target.canvas===t});return e.forEach(function(t){t.cancel()}),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach(function(t){t.cancel()}),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find(function(e){return e.cancel===t})},findAnimationsByTarget:function(t){return t?this.filter(function(e){return e.target===t}):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map(function(t,e){return v[e]-_[e]}):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map(function(t,e){return m(n,_[e],y[e],c)}):m(n,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=r,!o){if(!f(w,E,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,E,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",S=0,b=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),E.minX=i,E.minY=n,E.viewBoxWidth=r,E.viewBoxHeight=o,y?(E.width=r,E.height=o):(E.width=s(d),E.height=s(f),c=E.width/r,u=E.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=E.width-r*c,b=E.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),E}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function E(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),C(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),C(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),C=_(f,y,w),S=e.gestureScale;if(C)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=E(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y(function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),C(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=E(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),C(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=E,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach(function(e){i[e]=t[e]}),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach(function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s})}(0,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,function(t,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(e){this[e]!==i[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)},this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find(function(e){return!0===t[e]}):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),r.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e:e,selected:r}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach(function(i){e[i]=t[i]}),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach(function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})}),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e:e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter(function(e){return!e.onSelect({e:t})})),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){r.clear(),r._setBgOverlay(n,function(){s?r._enlivenObjects([s],function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)}):r.__setupCanvas.call(r,n,t,o,e)})},i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach(function(t,e){r.insertAt(t,e)}),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],function(e){r[t]=e[0],i[t]=!0,n&&n()}):this["set"+b.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},null,i):e&&e([])},_toDataURL:function(t,e){this.clone(function(i){e(i.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,i){this.clone(function(n){i(n.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(i,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,function(){i.renderAll(),t&&t(i)}),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=l>y||c>w;v=E||(l<.9*y||c<.9*w)&&y>h&&w>h,E&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach(function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])}),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var o=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,function(){var t=s?new o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof n?n=E[n]:n-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof r?r=C[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,o=b.util.sin(n)*r;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach(function(t){r[t]=e[t]}),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl(function(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,function(t){delete t.points,i&&i(t)},"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r}),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter(function(t){return t&&!t.isNeutralState()}),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,function(){var n=new b.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,function(t,n){e&&e(new b.Image(t,i),n)},null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach(function(t){t.applyTo(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=n,C[s+3]=S?m[s+3]:r}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(b-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+C*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+C*n+o,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&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 n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},ii={};function ni(t){var e=ii[t];if(void 0!==e)return e.exports;var i=ii[t]={exports:{}};return ei[t](i,i.exports,ni),i.exports}ni.d=(t,e)=>{for(var i in e)ni.o(e,i)&&!ni.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ni.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ri={};(()=>{let t;ni.d(ri,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ni(653).fabric:{version:"5.2.1"}})();var si,oi,ai,hi,li=ri.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(si||(si={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(oi||(oi={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(ai||(ai={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(hi||(hi={}));const ci=t=>"number"==typeof t&&!Number.isNaN(t),ui=t=>"string"==typeof t;var di,fi,gi,mi,pi,_i,vi,yi,wi,Ei,Ci;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(pi||(pi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(_i||(_i={}));let Si=class{get mediaType(){return new Map([["rect",si.DIMT_RECTANGLE],["quad",si.DIMT_QUADRILATERAL],["text",si.DIMT_TEXT],["arc",si.DIMT_ARC],["image",si.DIMT_IMAGE],["polygon",si.DIMT_POLYGON],["line",si.DIMT_LINE],["group",si.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Ke(this,fi,"f")){case oi.DIS_DEFAULT:return"default";case oi.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Ke(this,gi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Ke(this,gi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ze(this,gi,t,"f")}get coordinateBase(){return Ke(this,gi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(di.add(this),fi.set(this,void 0),gi.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!ci(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(oi.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(oi.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(oi.DIS_SELECTED):this.setState(oi.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)}),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ze(this,fi,t,"f")}getState(){return Ke(this,fi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,xi),actionName:"modifyPolygon",pointIndex:i}),t},{}),Ze(this,yi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map(t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2})),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce(function(t,e,n){return t["p"+n]=new li.Control({positionHandler:Ti,actionHandler:Oi(n>0?n-1:i,xi),actionName:"modifyPolygon",pointIndex:n}),t},{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=li.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Ke(this,yi,"f")&&this.setPolygon(Ke(this,yi,"f"))}setPolygon(t){if(!M(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ze(this,yi,JSON.parse(JSON.stringify(t)),"f")}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ke(this,yi,"f")?JSON.parse(JSON.stringify(Ke(this,yi,"f"))):null}};yi=new WeakMap;wi=new WeakMap,Ei=new WeakMap;const Ai=t=>{let e=(t=>t.split("\n").map(t=>t.split("\t")))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ze(this,Mi,JSON.parse(JSON.stringify(t)),"f")}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Ke(this,Mi,"f")?JSON.parse(JSON.stringify(Ke(this,Mi,"f"))):null}};Mi=new WeakMap;class Pi extends Si{constructor(t){super(new li.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(oi.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("selected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._fabricObject.on("deselected",()=>{this.setState(oi.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("deselected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map(t=>t.getDrawingItem())}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const ki=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Ni=t=>!!ui(t)&&""!==t,Bi=t=>!(!ki(t)||"id"in t&&!ci(t.id)||"lineWidth"in t&&!ci(t.lineWidth)||"fillStyle"in t&&!Ni(t.fillStyle)||"strokeStyle"in t&&!Ni(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Ni(t.fontFamily)||"fontSize"in t&&!ci(t.fontSize));class ji{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(P(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!R(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Ui,Vi;class Gi{constructor(){Ui.set(this,new Map),Vi.set(this,!1)}get disposed(){return Ke(this,Vi,"f")}on(t,e){t=t.toLowerCase();const i=Ke(this,Ui,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Ke(this,Ui,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Ke(this,Ui,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Ke(this,Ui,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Ke(this,Ui,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Ze(this,Vi,!0,"f")}}function Wi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Yi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Hi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Ui=new WeakMap,Vi=new WeakMap;const Xi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};class zi{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*r[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return zi.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return zi.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return zi.multiply(t,[e,0,0,0,i,0,0,0,1])}}var qi,Ki,Zi,Ji,$i,Qi,tn,en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,En,Cn,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Er;class Cr{static createDrawingStyle(t){if(!Bi(t))throw new Error("Invalid style definition.");let e,i=Cr.USER_START_STYLE_ID;for(;Ke(Cr,qi,"f",Ki).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Ke(Cr,qi,"f",Zi))n.hasOwnProperty(t)||(n[t]=Ke(Cr,qi,"f",Zi)[t]);return Ke(Cr,qi,"f",Ki).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Ke(Cr,qi,"f",Ki).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Ke(Cr,qi,"f",Ki).values())))}static _updateDrawingStyle(t,e){if(!Bi(e))throw new Error("Invalid style definition.");const i=Ke(Cr,qi,"f",Ki).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}qi=Cr,Cr.STYLE_BLUE_STROKE=1,Cr.STYLE_GREEN_STROKE=2,Cr.STYLE_ORANGE_STROKE=3,Cr.STYLE_YELLOW_STROKE=4,Cr.STYLE_BLUE_STROKE_FILL=5,Cr.STYLE_GREEN_STROKE_FILL=6,Cr.STYLE_ORANGE_STROKE_FILL=7,Cr.STYLE_YELLOW_STROKE_FILL=8,Cr.STYLE_BLUE_STROKE_TRANSPARENT=9,Cr.STYLE_GREEN_STROKE_TRANSPARENT=10,Cr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Cr.USER_START_STYLE_ID=1024,Ki={value:new Map([[Cr.STYLE_BLUE_STROKE,{id:Cr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_GREEN_STROKE,{id:Cr.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_ORANGE_STROKE,{id:Cr.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_YELLOW_STROKE,{id:Cr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_BLUE_STROKE_FILL,{id:Cr.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_GREEN_STROKE_FILL,{id:Cr.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_ORANGE_STROKE_FILL,{id:Cr.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_YELLOW_STROKE_FILL,{id:Cr.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Cr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Cr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Cr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Cr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Zi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(li.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(li.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject(function(t){t.dispose&&t.dispose()}),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),li.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},li.Object.prototype.transparentCorners=!1,li.Object.prototype.cornerSize=20,li.Object.prototype.touchCornerSize=100,li.Object.prototype.cornerColor="rgb(254,142,20)",li.Object.prototype.cornerStyle="circle",li.Object.prototype.strokeUniform=!0,li.Object.prototype.hasBorders=!1,li.Canvas.prototype.containerClass="",li.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=li.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},li.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;ii&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Sr{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new li.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])},0)}}),e.on("before:selection:cleared",function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.fabricCanvas.id=e,this.id=e,e){case Sr.DDN_LAYER_ID:n=Cr.getDrawingStyle(Cr.STYLE_BLUE_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_BLUE_STROKE_FILL);break;case Sr.DBR_LAYER_ID:n=Cr.getDrawingStyle(Cr.STYLE_ORANGE_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_ORANGE_STROKE_FILL);break;case Sr.DLR_LAYER_ID:n=Cr.getDrawingStyle(Cr.STYLE_GREEN_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_GREEN_STROKE_FILL);break;default:n=Cr.getDrawingStyle(Cr.STYLE_YELLOW_STROKE),r=Cr.getDrawingStyle(Cr.STYLE_YELLOW_STROKE_FILL)}for(let t of Si.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Cr.getDrawingStyle(t.styleId);return Cr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems(e=>e._mediaType===t);for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Cr.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Cr.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Cr.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Si))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Si.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Cr.getDrawingStyle(t.styleId);else{s=Cr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Si.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Cr.getDrawingStyle(t.styleId);else{s=Cr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Cr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase()):e=Si.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Si.arrStyleSelectors;const n=Cr.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&si.DIMT_RECTANGLE&&n.push("rect"),i&si.DIMT_QUADRILATERAL&&n.push("quad"),i&si.DIMT_TEXT&&n.push("text"),i&si.DIMT_ARC&&n.push("arc"),i&si.DIMT_IMAGE&&n.push("image"),i&si.DIMT_POLYGON&&n.push("polygon"),i&si.DIMT_LINE&&n.push("line");const r=[];e&oi.DIS_DEFAULT&&r.push("default"),e&oi.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Sr.DDN_LAYER_ID=1,Sr.DBR_LAYER_ID=2,Sr.DLR_LAYER_ID=3,Sr.USER_DEFINED_LAYER_BASE_ID=100,Sr.TIP_LAYER_ID=999;class br{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Sr(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Tr extends Di{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Ji.set(this,void 0),$i.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ze(this,$i,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},Ke(this,Ji,"f")),"f")}getDuration(){return Ke(this,Ji,"f")}}Ji=new WeakMap,$i=new WeakMap;class Ir{constructor(){Qi.add(this),tn.set(this,void 0),en.set(this,void 0),nn.set(this,void 0),rn.set(this,!0),this._drawingLayerManager=new br}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Sr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Sr.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Sr.TIP_LAYER_ID)}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ki(e=t)&&L(e.topLeftPoint)&&ci(e.width))||e.width<=0||!ci(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ze(this,tn,JSON.parse(JSON.stringify(t)),"f"),Ke(this,tn,"f").coordinateBase||(Ke(this,tn,"f").coordinateBase="view"),Ze(this,nn,t.duration,"f"),Ke(this,Qi,"m",hn).call(this)}getTipConfig(){return Ke(this,tn,"f")?Ke(this,tn,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ze(this,rn,t,"f")}isTipVisible(){return Ke(this,rn,"f")}updateTipMessage(t){if(!Ke(this,tn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Cr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Sr.TIP_LAYER_ID)||this._createDrawingLayer(Sr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Ke(this,Qi,"m",sn).call(this,t,Ke(this,tn,"f").topLeftPoint.x,Ke(this,tn,"f").topLeftPoint.y,Ke(this,tn,"f").width,Ke(this,tn,"f").coordinateBase,this._tipStyleId),Ke(this,Qi,"m",on).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Ke(this,rn,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Ke(this,en,"f")&&clearTimeout(Ke(this,en,"f")),Ke(this,nn,"f")>=0&&Ze(this,en,setTimeout(()=>{Ke(this,Qi,"m",an).call(this)},Ke(this,nn,"f")),"f")}}tn=new WeakMap,en=new WeakMap,nn=new WeakMap,rn=new WeakMap,Qi=new WeakSet,sn=function(t,e,i,n,r,s){const o=new Tr(t,e,i,n,s);return o.coordinateBase=r,o},on=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},an=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},hn=function(){if(!this._tip)return;const t=Ke(this,tn,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class xr extends HTMLElement{constructor(){super(),ln.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ze(this,ln,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Ke(this,ln,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach(t=>t.remove())}}ln=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",xr);class Or extends Ir{static get engineResourcePath(){const t=B(jt.engineResourcePaths);return"DCV"===jt._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Or._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Or._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Or.engineResourcePath)}static async createInstance(t){const e=new Or;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Or.engineResourcePath)),await e.setUIElement(t||Or.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Ke(this,yn,"f")){if(Ze(this,yn,t,"f"),Ke(this,cn,"m",Cn).call(this))Ze(this,gn,null,"f"),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Ke(this,gn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ze(this,gn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Ke(this,cn,"m",Cn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Ke(this,yn,"f")}get disposed(){return Ke(this,En,"f")}constructor(){super(),cn.add(this),un.set(this,void 0),dn.set(this,void 0),fn.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",gn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._poweredBy=null,mn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,pn.set(this,!1),_n.set(this,!1),vn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Ke(this,cn,"m",xn).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout(()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Ke(this,cn,"m",In).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Or._onLog&&Or._onLog("window resize event triggered."),Ke(this,vn,"f").width===document.documentElement.clientWidth&&Ke(this,vn,"f").height===document.documentElement.clientHeight||(Ke(this,vn,"f").width=document.documentElement.clientWidth,Ke(this,vn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},yn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Ke(this,cn,"m",Cn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout(()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)},0)}),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},wn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach(t=>Or._transformCoordinates(t,i,n,r,s,o,a));const c=new Fi({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),Ke(this,wn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case ht.CRIT_ORIGINAL_IMAGE:break;case ht.CRIT_BARCODE:m=this.getDrawingLayer(Sr.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Cr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ht.CRIT_TEXT_LINE:m=this.getDrawingLayer(Sr.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,h,l,c,u,d,f,p):g(m,t.location.points,h,l,c,u,d,f,p,Cr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ht.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Sr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===pt.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Cr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case ht.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(Sr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===pt.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Cr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case ht.CRIT_PARSED_RESULT:case ht.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}if(t.decodedBarcodesResult)for(let e=0;eOr._transformCoordinates(t,h,l,c,u,d,f));if(t.recognizedTextLinesResult)for(let e=0;eOr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult){if(t.processedDocumentResult.detectedQuadResultItems)for(let e=0;eOr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult.deskewedImageResultItems)for(let e=0;eOr._transformCoordinates(t,h,l,c,u,d,f))}}},En.set(this,!1),this.eventHandler=new Gi,this.eventHandler.on("content:updated",()=>{Ke(this,un,"f")&&clearTimeout(Ke(this,un,"f")),Ze(this,un,setTimeout(()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)},0),"f")}),this.eventHandler.on("videoEl:resized",()=>{Ke(this,dn,"f")&&clearTimeout(Ke(this,dn,"f")),Ze(this,dn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Xi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),Ke(this,cn,"m",Cn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(qe.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ze(this,gn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||Ke(this,cn,"m",Cn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Ke(this,cn,"m",Cn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Ke(this,cn,"m",xn).call(this),Ke(this,cn,"m",Cn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Ke(this,cn,"m",Cn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver(t=>{var e;Or._onLog&&Or._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()}));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Ke(this,vn,"f").width=document.documentElement.clientWidth,Ke(this,vn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Ke(this,cn,"m",Cn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Ke(this,cn,"m",xn).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ze(this,gn,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Ke(this,gn,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Ke(this,gn,"f"))return;if(Ke(this,gn,"f").style.objectFit=t,Ke(this,cn,"m",Cn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();Ke(this,cn,"m",On).call(this,e,i),Ke(this,cn,"m",Sn).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(Ke(this,cn,"m",Cn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=Ke(this,gn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Ke(this,gn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){R(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):P(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=ji.convert(this.scanRegion,t.width,t.height,this);Ze(this,mn,e,"f"),Ke(this,fn,"f")&&clearTimeout(Ke(this,fn,"f")),Ze(this,fn,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Ke(this,cn,"m",Sn).call(this,t,e),Ke(this,cn,"m",On).call(this,t,e)},0),"f")}getConvertedRegion(){return Ke(this,mn,"f")}setScanRegion(t){if(null!=t&&!R(t)&&!P(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Ke(this,gn,"f").videoWidth,i=Ke(this,gn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=Ke(this,gn,"f").videoWidth,e=Ke(this,gn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove()),Ke(this,wn,"f").length=0}dispose(){this._unbindUI(),Ze(this,En,!0,"f")}}un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,En=new WeakMap,cn=new WeakSet,Cn=function(){return"disabled"!==this._singleFrameMode},Sn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},bn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Tn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},In=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},xn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},On=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach(e=>t.attachShader(i,e)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);Ze(this,Dn,{program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},"f"),Ze(this,Ln,e(t),"f"),Ze(this,An,i(t),"f"),Ze(this,Rn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,o,m)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[hi.GREY,hi.GREY32].includes(p)?1:0);let _,v,y=zi.translate(zi.identity(),-1,-1);y=zi.scale(y,2,2),y=zi.scale(y,1/t.canvas.width,1/t.canvas.height),_=zi.translate(y,u,d),_=zi.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=zi.translate(zi.identity(),1,0),v=zi.scale(v,-1,1),v=zi.translate(v,a/i,h/n),v=zi.scale(v,l/i,c/n)):(v=zi.translate(zi.identity(),a/i,h/n),v=zi.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,Ke(this,An,"f"),e),y(t,Ke(this,Dn,"f"),Ke(this,Ln,"f"),Ke(this,An,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){Rr._onLog&&Rr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Rr._onLog&&Rr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===hi.GREY?hi.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Rr._onLog&&Rr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(Rr._onLog&&(r=Date.now(),Rr._onLog("transformPixelFormat(), START: "+r)),e===i)return Rr._onLog&&Rr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[hi.RGBA,hi.RBGA,hi.GRBA,hi.GBRA,hi.BRGA,hi.BGRA];if(o.includes(e))if(i===hi.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=Rr._onLog)||void 0===n||n.call(Rr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||hi.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(hi.GREY===y&&w.length{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Dr{static get version(){return"4.2.3-dev-20250812165927"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find(t=>e.includes(t.label.toLowerCase()));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!r.length)return null;const s=r.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(s)return s.deviceId;const o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(qe.OS))return Dr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some(e=>t.includes(e))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(qe.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise(async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise(t=>{g=t}),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise(t=>{setTimeout(t,1e3)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}})}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!Ke(this,qn,"f"))return"closed";if("pending"===Ke(this,qn,"f"))return"opening";if("fulfilled"===Ke(this,qn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Dr.isStorageAvailable("localStorage")?Ze(this,Yn,!0,"f"):(Ze(this,Yn,!1,"f"),console.warn("Local storage is unavailable")):Ze(this,Yn,!1,"f")}get ifSaveLastUsedCamera(){return Ke(this,Yn,"f")}get isVideoPlaying(){return!(!Ke(this,Nn,"f")||Ke(this,Nn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Ke(this,tr,"f"))||void 0===e||e.removeEventListener("click",Ke(this,Qn,"f")),null===(i=Ke(this,tr,"f"))||void 0===i||i.removeEventListener("touchend",Ke(this,Qn,"f")),null===(n=Ke(this,tr,"f"))||void 0===n||n.removeEventListener("touchmove",Ke(this,$n,"f")),Ze(this,tr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(qe.OS)?(t.addEventListener("touchend",Ke(this,Qn,"f")),t.addEventListener("touchmove",Ke(this,$n,"f"))):t.addEventListener("click",Ke(this,Qn,"f")))}get tapFocusEventBoundEl(){return Ke(this,tr,"f")}get disposed(){return Ke(this,lr,"f")}constructor(t){var e,i;kn.add(this),Nn.set(this,null),Bn.set(this,void 0),this._zoomPreSetting=null,jn.set(this,()=>{"opened"===this.state&&Ke(this,rr,"f").fire("resumed",null,{target:this,async:!1})}),Un.set(this,()=>{Ke(this,rr,"f").fire("paused",null,{target:this,async:!1})}),Vn.set(this,void 0),Gn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Wn.set(this,void 0),Yn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,Hn.set(this,void 0),Xn.set(this,!0),zn.set(this,void 0),qn.set(this,void 0),Kn.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},Zn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Ke(this,Nn,"f")).objectFit,s=this.getResolution(),o=Ke(this,Nn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=Ke(this,Nn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},Jn.set(this,!1),$n.set(this,()=>{Ze(this,Jn,!0,"f")}),Qn.set(this,async t=>{var e;if(Ke(this,Jn,"f"))return void Ze(this,Jn,!1,"f");if(!Ke(this,Zn,"f"))return;if(!this.isVideoPlaying)return;if(!Ke(this,Bn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Dr._onLog&&(c=Date.now());try{await Ke(this,kn,"m",yr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Dr._onLog)throw Dr._onLog(t),t}Dr._onLog&&Dr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Dr._onLog&&Dr._onLog("Back to continuous focus."),null===(t=Ke(this,Bn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),Ke(this,rr,"f").fire("tapfocus",null,{target:this,async:!1})}),tr.set(this,null),er.set(this,1),ir.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Ke(this,Nn,"f"))return;const t=Ke(this,er,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Ke(this,Nn,"f").style.transform="";else{const e=window.getComputedStyle(Ke(this,Nn,"f")).objectFit,i=Ke(this,Nn,"f").videoWidth,n=Ke(this,Nn,"f").videoHeight,{width:r,height:s}=Ke(this,Nn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-Ke(this,ir,"f").x),c=h*(1-1/t)*(n/2-Ke(this,ir,"f").y);Ke(this,Nn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},nr.set(this,function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===hi.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Dr._onLog&&Dr._onLog("document visible. video paused: "+(null===(t=Ke(this,Nn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Dr._onLog&&Dr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Dr._onLog&&Dr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Ke(this,kn,"m",gr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Dr._onLog&&Dr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Dr._onLog&&Dr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Ke(this,kn,"m",gr).call(this)}}}else"hidden"===document.visibilityState&&(Dr._onLog&&Dr._onLog("document hidden. video paused: "+(null===(e=Ke(this,Nn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),lr.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout(()=>{Dr.onWarning&&Dr.onWarning("The browser is too old or the page is loaded from an insecure origin.")},0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Ze(this,rr,new Gi,"f"),this.imageDataGetter=new Rr,document.addEventListener("visibilitychange",Ke(this,hr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Ke(this,jn,"f")),t.addEventListener("pause",Ke(this,Un,"f")),Ze(this,Nn,t,"f")}getVideoEl(){return Ke(this,Nn,"f")}releaseVideoEl(){var t,e;null===(t=Ke(this,Nn,"f"))||void 0===t||t.removeEventListener("play",Ke(this,jn,"f")),null===(e=Ke(this,Nn,"f"))||void 0===e||e.removeEventListener("pause",Ke(this,Un,"f")),Ze(this,Nn,null,"f")}isVideoLoaded(){return!!Ke(this,Nn,"f")&&(this.videoSrc?0!==Ke(this,Nn,"f").readyState:4===Ke(this,Nn,"f").readyState)}async open(){if(Ke(this,zn,"f")&&!Ke(this,Xn,"f")){if("pending"===Ke(this,qn,"f"))return Ke(this,zn,"f");if("fulfilled"===Ke(this,qn,"f"))return}Ke(this,rr,"f").fire("before:open",null,{target:this}),await Ke(this,kn,"m",gr).call(this),Ke(this,rr,"f").fire("played",null,{target:this,async:!1}),Ke(this,rr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Ke(this,rr,"f").fire("before:close",null,{target:this});const t=Ke(this,zn,"f");if(Ke(this,kn,"m",pr).call(this),t&&"pending"===Ke(this,qn,"f")){try{await t}catch(t){}if(!1===Ke(this,Xn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Ze(this,zn,null,"f"),Ze(this,qn,null,"f"),Ke(this,rr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Ke(this,Nn,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Ke(this,Nn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Ke(this,Vn,"f").video&&(Ke(this,Vn,"f").video={}),delete Ke(this,Vn,"f").video.facingMode,Ke(this,Vn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ke(this,Xn,"f"))){Ke(this,rr,"f").fire("before:camera:change",[],{target:this,async:!1}),await Ke(this,kn,"m",mr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ke(this,Gn,"f")}}async switchToFrontCamera(t){if("object"!=typeof Ke(this,Vn,"f").video&&(Ke(this,Vn,"f").video={}),(null==t?void 0:t.resolution)&&(Ke(this,Vn,"f").video.width={ideal:t.resolution.width},Ke(this,Vn,"f").video.height={ideal:t.resolution.height}),delete Ke(this,Vn,"f").video.deviceId,Ke(this,Vn,"f").video.facingMode={exact:"user"},Ze(this,Wn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ke(this,Xn,"f"))){Ke(this,rr,"f").fire("before:camera:change",[],{target:this,async:!1}),Ke(this,kn,"m",mr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ke(this,Gn,"f")}}getCamera(){var t;if(Ke(this,Gn,"f"))return Ke(this,Gn,"f");{let e=(null===(t=Ke(this,Vn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind);return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Ke(this,Vn,"f").video&&(Ke(this,Vn,"f").video={}),i?(Ke(this,Vn,"f").video.width={exact:t},Ke(this,Vn,"f").video.height={exact:e}):(Ke(this,Vn,"f").video.width={ideal:t},Ke(this,Vn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Ke(this,Xn,"f"))return null;Ke(this,rr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Ke(this,kn,"m",mr).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Ke(this,Nn,"f"))return{width:Ke(this,Nn,"f").videoWidth,height:Ke(this,Nn,"f").videoHeight};if(Ke(this,Bn,"f")){const t=Ke(this,Bn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Ke(this,Nn,"f").videoWidth,height:Ke(this,Nn,"f").videoHeight};{const t={width:0,height:0};let e=Ke(this,Vn,"f").video.width||0,i=Ke(this,Vn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Ke(this,or,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Ke(this,Gn,"f"))||void 0===u?void 0:u.deviceId;let e=Ke(this,or,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Ke(this,or,"f").set(d,e),Ze(this,Kn,!0,"f");try{for(let t of this.detectedResolutions){await Ke(this,Bn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Ke(this,kn,"m",ur).call(this);const i=Ke(this,Bn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Ke(this,kn,"m",pr).call(this),Ze(this,Kn,!1,"f"),t}try{await Ke(this,kn,"m",gr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Ze(this,Kn,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=Ke(this,Vn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=Ke(this,Vn,"f"))||void 0===o?void 0:o.video)||void 0===a?void 0:a.deviceId)||void 0===h?void 0:h.ideal)||(null===(c=null===(l=Ke(this,Vn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Ke(this,or,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Ke(this,or,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Ze(this,Vn,JSON.parse(JSON.stringify(t)),"f"),Ze(this,Wn,null,"f"),e&&await Ke(this,kn,"m",mr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Ke(this,Vn,"f")))}resetMediaStreamConstraints(){Ze(this,Vn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ke(this,Bn,"f").getCapabilities?Ke(this,Bn,"f").getCapabilities():{}}getCameraSettings(){if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ke(this,Bn,"f").getSettings()}async turnOnTorch(){if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ke(this,Bn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ke(this,Bn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ar(t,n.min,n.step,n.max)),await Ke(this,Bn,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ar(t,n.min,n.step,n.max)),await Ke(this,Bn,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Ke(this,Bn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Ar(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Ke(this,Bn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Ke(this,kn,"m",yr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Ke(this,Bn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}enableTapToFocus(){Ze(this,Zn,!0,"f")}disableTapToFocus(){Ze(this,Zn,!1,"f")}isTapToFocusEnabled(){return Ke(this,Zn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"===this.state){t.centerPoint?Ke(this,kn,"m",wr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Ke(this,kn,"m",Er).call(this,Ke(this,ir,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}else this._zoomPreSetting=t}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Ke(this,er,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Ke(this,Bn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ar(t,n.min,n.step,n.max)),await Ke(this,Bn,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Ke(this,kn,"m",wr).call(this,e),Ze(this,er,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Ke(this,er,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Ze(this,ir,{x:t.width/2,y:t.height/2},"f")}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Ke(this,Kn,"f"))return null;const e=Date.now();Dr._onLog&&Dr._onLog("getFrameData() START: "+e);const i=Ke(this,Nn,"f").videoWidth,n=Ke(this,Nn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=hi.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=Ke(this,er,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=Ke(this,ir,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(Ke(this,Nn,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Dr._onLog&&Dr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Ke(this,nr,"f")}}on(t,e){if(!Ke(this,sr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Ke(this,rr,"f").on(t,e)}off(t,e){Ke(this,rr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Ke(this,rr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Ke(this,hr,"f")),Ze(this,lr,!0,"f")}}var Lr,Mr,Fr,Pr,kr,Nr,Br,jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs;Nn=new WeakMap,Bn=new WeakMap,jn=new WeakMap,Un=new WeakMap,Vn=new WeakMap,Gn=new WeakMap,Wn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,kn=new WeakSet,cr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Ke(this,Wn,"f"))delete t.video.facingMode,t.video.deviceId={exact:Ke(this,Wn,"f")};else if(this.ifSaveLastUsedCamera&&Dr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(qe.OS)?(await this._getCameras(!1),Ke(this,kn,"m",ur).call(this),e=Dr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(qe.OS)||(await this._getCameras(!1),Ke(this,kn,"m",ur).call(this),e=Dr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},ur=function(){if(Ke(this,Xn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},dr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Dr._onLog&&Dr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise(t=>setTimeout(t,r)),Ke(this,kn,"m",ur).call(this));try{Dr._onLog&&Dr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Ke(this,kn,"m",ur).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Dr._onLog&&Dr._onLog(t.message||t)}}};if(await r(t),!n&&"object"==typeof t.video&&(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t)),!n)){const t=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let e of t){const t={video:{deviceId:{ideal:e.deviceId},facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}}};if(await r(t),n)break}}if(!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach(t=>{t.stop()}),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},fr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),Ze(this,Bn,null,"f")},gr=async function(){Ze(this,Xn,!1,"f");const t=Ze(this,Hn,Symbol(),"f");if(Ke(this,zn,"f")&&"pending"===Ke(this,qn,"f")){try{await Ke(this,zn,"f")}catch(t){}Ke(this,kn,"m",ur).call(this)}if(t!==Ke(this,Hn,"f"))return;const e=Ze(this,zn,(async()=>{Ze(this,qn,"pending","f");try{if(this.videoSrc){if(!Ke(this,Nn,"f"))throw new Error("'videoEl' should be set.");await Dr.playVideo(Ke(this,Nn,"f"),this.videoSrc,this.cameraOpenTimeout),Ke(this,kn,"m",ur).call(this)}else{let t=await Ke(this,kn,"m",cr).call(this);Ke(this,kn,"m",fr).call(this);let e=await Ke(this,kn,"m",dr).call(this,t);await this._getCameras(!1),Ke(this,kn,"m",ur).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Ke(this,Vn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Ke(this,Wn,"f")||this.ifSaveLastUsedCamera&&Dr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Dr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:s},e=await Ke(this,kn,"m",dr).call(this,t),Ke(this,kn,"m",ur).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Ze(this,Wn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Dr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Ke(this,Wn,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Ke(this,Nn,"f")&&(await Dr.playVideo(Ke(this,Nn,"f"),e,this.cameraOpenTimeout),Ke(this,kn,"m",ur).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Ze(this,Bn,s[0],"f"),Ze(this,Gn,r,"f")}}catch(t){throw Ke(this,kn,"m",pr).call(this),Ze(this,qn,null,"f"),t}Ze(this,qn,"fulfilled","f")})(),"f");return e},mr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Ke(this,Gn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Ke(this,kn,"m",gr).call(this);const n=this.getResolution();e&&e!==Ke(this,Gn,"f").deviceId&&Ke(this,rr,"f").fire("camera:changed",[Ke(this,Gn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Ke(this,rr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Ke(this,rr,"f").fire("played",null,{target:this,async:!1})},pr=function(){Ke(this,kn,"m",fr).call(this),Ze(this,Gn,null,"f"),Ke(this,Nn,"f")&&(Ke(this,Nn,"f").srcObject=null,this.videoSrc&&(Ke(this,Nn,"f").pause(),Ke(this,Nn,"f").currentTime=0)),Ze(this,Xn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},_r=async function t(e,i){const n=t=>{if(!Ke(this,Bn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Ke(this,Bn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Ar(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Ke(this,Bn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise(t=>{setTimeout(t,r)}),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Ke(this,Nn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:hi.RGBA,bufferContainer:d}))return Ke(this,kn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await Ke(this,kn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await Ke(this,kn,"m",_r).call(this,e,c);if(a>h)return await Ke(this,kn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await Ke(this,kn,"m",t).call(this,e,o,a,c,h);let u=await Ke(this,kn,"m",_r).call(this,e,l);if(u>a&&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!==Ke(this,er,"f")){const t=Ke(this,er,"f"),e=Ke(this,ir,"f");l/=t,c/=t,a=(1-1/t)*e.x+a/t,h=(1-1/t)*e.y+h/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:a,focusT:h,focusW:l,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Ar(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ar(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ar(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await Ke(this,kn,"m",_r).call(this,t,s),a=await Ke(this,kn,"m",_r).call(this,t,r),h=await Ke(this,kn,"m",_r).call(this,t,n);if(a>h&&ho&&a>o){let e=await Ke(this,kn,"m",_r).call(this,t,i);const r=await Ke(this,kn,"m",vr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await Ke(this,kn,"m",vr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},wr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Ze(this,ir,{x:i,y:n},"f")},Er=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Dr.browserInfo=qe,Dr.onWarning=null===(Pn=null===window||void 0===window?void 0:window.console)||void 0===Pn?void 0:Pn.warn;class gs{constructor(t){Lr.add(this),Mr.set(this,void 0),Fr.set(this,0),Pr.set(this,void 0),kr.set(this,0),Nr.set(this,!1),Ze(this,Mr,t,"f")}startCharging(){Ke(this,Nr,"f")||(gs._onLog&&gs._onLog("start charging."),Ke(this,Lr,"m",jr).call(this),Ze(this,Nr,!0,"f"))}stopCharging(){Ke(this,Pr,"f")&&clearTimeout(Ke(this,Pr,"f")),Ke(this,Nr,"f")&&(gs._onLog&&gs._onLog("stop charging."),Ze(this,Fr,Date.now()-Ke(this,kr,"f"),"f"),Ze(this,Nr,!1,"f"))}}Mr=new WeakMap,Fr=new WeakMap,Pr=new WeakMap,kr=new WeakMap,Nr=new WeakMap,Lr=new WeakSet,Br=function(){jt.cfd(1),gs._onLog&&gs._onLog("charge 1.")},jr=function t(){0==Ke(this,Fr,"f")&&Ke(this,Lr,"m",Br).call(this),Ze(this,kr,Date.now(),"f"),Ke(this,Pr,"f")&&clearTimeout(Ke(this,Pr,"f")),Ze(this,Pr,setTimeout(()=>{Ze(this,Fr,0,"f"),Ke(this,Lr,"m",t).call(this)},Ke(this,Mr,"f")-Ke(this,Fr,"f")),"f")};class ms{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Ke(this,Ur,"f",Wr)<100)){if(Ze(this,Ur,e,"f",Wr),Ke(this,Ur,"f",Vr).size&&(t=Ke(this,Ur,"f",Vr).values().next().value,this.beepSoundSource==t.src?(Ke(this,Ur,"f",Vr).delete(t),t.play()):t=null),!t)if(Ke(this,Ur,"f",Gr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{Ke(this,Ur,"f",Gr).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Ke(this,Ur,"f",Gr).delete(t),Ke(this,Ur,"f",Vr).add(t)})}else Ke(this,Ur,"f",Yr)||(Ze(this,Ur,!0,"f",Yr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Ke(this,Ur,"f",Gr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(ms.vibrateDuration)}}}Ur=ms,Vr={value:new Set},Gr={value:new Set},Wr={value:0},Yr={value:!1},ms.allowBeep=!0,ms.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",ms.allowVibrate=!0,ms.vibrateDuration=300;const ps=new Map([[hi.GREY,v.IPF_GRAYSCALED],[hi.RGBA,v.IPF_ABGR_8888]]),_s="function"==typeof BigInt?t=>BigInt(t):t=>t,vs=(_s("0x00"),_s("0xFFFFFFFFFFFFFFFF"),_s("0xFE3BFFFF"),_s("0x003007FF")),ys=(_s("0x0003F800"),_s("0x1"),_s("0x2"),_s("0x4"),_s("0x8"),_s("0x10"),_s("0x20"),_s("0x40"),_s("0x80"),_s("0x100"),_s("0x200"),_s("0x400"),_s("0x800"),_s("0x1000"),_s("0x2000"),_s("0x4000"),_s("0x8000"),_s("0x10000"),_s("0x20000"),_s("0x00040000"),_s("0x01000000"),_s("0x02000000"),_s("0x04000000")),ws=_s("0x08000000");_s("0x10000000"),_s("0x20000000"),_s("0x40000000"),_s("0x00080000"),_s("0x80000000"),_s("0x100000"),_s("0x200000"),_s("0x400000"),_s("0x800000"),_s("0x1000000000"),_s("0x3F0000000000000"),_s("0x100000000"),_s("0x10000000000000"),_s("0x20000000000000"),_s("0x40000000000000"),_s("0x80000000000000"),_s("0x100000000000000"),_s("0x200000000000000"),_s("0x200000000"),_s("0x400000000"),_s("0x800000000"),_s("0xC00000000"),_s("0x2000000000"),_s("0x4000000000");class Es extends nt{static set _onLog(t){Ze(Es,Xr,t,"f",zr),Dr._onLog=t,gs._onLog=t}static get _onLog(){return Ke(Es,Xr,"f",zr)}static async detectEnvironment(){return await(async()=>({wasm:Je,worker:$e,getUserMedia:Qe,camera:await ti(),browser:qe.browser,version:qe.version,OS:qe.OS}))()}static async testCameraAccess(){const t=await Dr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Or))throw new TypeError("Invalid view.");if(!Es._isRTU&&(null===(e=kt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=kt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await jt.loadWasm(),await kt.license.dynamsoft()}const n=new Es(t);return Es.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{Es.onWarning&&Es.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})},0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout(()=>{Es.onWarning&&Es.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})},0)),n}get isEnableMirroring(){return this._isEnableMirroring}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ze(this,Jr,t,"f")}get singleFrameMode(){return Ke(this,Jr,"f")}get _isFetchingStarted(){return Ke(this,ns,"f")}get disposed(){return Ke(this,hs,"f")}constructor(t){if(super(),Hr.add(this),qr.set(this,"closed"),Kr.set(this,void 0),Zr.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,Jr.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},$r.set(this,(t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?hi.GREY:hi.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===hi.GREY?a.width:4*a.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:a.data,width:a.width,height:a.height,stride:o,format:ps.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:ft.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:Ke(this,Qr,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():ji.convert(Ke(this,es,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Ke(this,$r,"f").call(this,t,t.width,t.height,e);Ke(this,Kr,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},Qr.set(this,function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===v.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(qe.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",()=>{Ke(this,as,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("camera:changed",()=>{this.clearBuffer()}),this._on("before:resolution:change",()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("resolution:changed",()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})}),this._on("paused",()=>{Ke(this,as,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{Ke(this,ss,"f").tapToFocus&&Ke(this,as,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(Ke(this,Hr,"m",ls).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Es._onLog&&(Es._onLog("intermediateResultUnits:"),Es._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===_t.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===_t.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Es._onLog&&(Es._onLog("hasLocalizedBarcodes:"),Es._onLog(h)),Ke(this,ss,"f").autoZoom||Ke(this,ss,"f").enhancedFocus)if(a)Ke(this,os,"f").autoZoomInFrameArray.length=0,Ke(this,os,"f").autoZoomOutFrameCount=0,Ke(this,os,"f").frameArrayInIdealZoom.length=0,Ke(this,os,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Ke(this,ss,"f").autoZoom&&Ke(this,as,"f").startCharging()},a=async t=>{await this.setFocus(t),Ke(this,ss,"f").enhancedFocus&&Ke(this,as,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Ke(this,os,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Ke(this,os,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Ke(this,os,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+Ke(this,os,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Es._onLog&&(Es._onLog("detectionArea:"),Es._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Yi(a.y-i)>0&&Yi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Hi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Hi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Hi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Hi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Or._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Es._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Cr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===_t.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Ri({points:i},e);t.addDrawingItems([r])}}}if(Es._onLog&&(Es._onLog("intersectedResults:"),Es._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==ys||t.possibleFormats==ws);if(t.length||(t=s.filter(t=>t.possibleFormats==vs),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{}),Ke(this,os,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=Ke(this,os,"f").autoZoomInFrameLimit[1]){Ke(this,os,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,Ke(this,os,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/Ke(this,os,"f").autoZoomInMaxTimes),Ke(this,os,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(Ke(this,os,"f").minValue,u),u=Math.min(Ke(this,os,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Ke(this,os,"f").autoZoomInFrameArray.length=0,Ke(this,os,"f").frameArrayInIdealZoom.push(!0),Ke(this,os,"f").frameArrayInIdealZoom.splice(0,Ke(this,os,"f").frameArrayInIdealZoom.length-Ke(this,os,"f").frameLimitInIdealZoom[0]),Ke(this,os,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=Ke(this,os,"f").frameLimitInIdealZoom[1]&&(Ke(this,os,"f").frameArrayInIdealZoom.length=0,Ke(this,ss,"f").enhancedFocus)){const e=m.points;try{await a({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Ke(this,ss,"f").autoZoom&&Ke(this,ss,"f").enhancedFocus&&(Ke(this,os,"f").autoFocusFrameArray.push(!0),Ke(this,os,"f").autoFocusFrameArray.splice(0,Ke(this,os,"f").autoFocusFrameArray.length-Ke(this,os,"f").autoFocusFrameLimit[0]),Ke(this,os,"f").autoFocusFrameArray.filter(t=>!0===t).length>=Ke(this,os,"f").autoFocusFrameLimit[1])){Ke(this,os,"f").autoFocusFrameArray.length=0;try{const t=m.points;await a({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Ke(this,ss,"f").autoZoom){if(Ke(this,os,"f").autoZoomInFrameArray.push(!1),Ke(this,os,"f").autoZoomInFrameArray.splice(0,Ke(this,os,"f").autoZoomInFrameArray.length-Ke(this,os,"f").autoZoomInFrameLimit[0]),Ke(this,os,"f").autoZoomOutFrameCount++,Ke(this,os,"f").frameArrayInIdealZoom.push(!1),Ke(this,os,"f").frameArrayInIdealZoom.splice(0,Ke(this,os,"f").frameArrayInIdealZoom.length-Ke(this,os,"f").frameLimitInIdealZoom[0]),Ke(this,os,"f").autoZoomOutFrameCount>=Ke(this,os,"f").autoZoomOutFrameLimit){Ke(this,os,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Ke(this,os,"f").autoZoomOutStepRate,Ke(this,os,"f").autoZoomOutMinStep);n=Math.max(Ke(this,os,"f").minValue,n),n=Math.min(Ke(this,os,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Ke(this,ss,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!Ke(this,ss,"f").autoZoom&&Ke(this,ss,"f").enhancedFocus&&(Ke(this,os,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},Ze(this,as,new gs(1e4),"f")}setCameraView(t){if(!(t instanceof Or))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Ke(this,Hr,"m",ls).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Ke(this,Hr,"m",ls).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Ke(this,Hr,"m",ls).call(this)?Ke(this,qr,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,Ke(this,Hr,"m",ls).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(Ke(this,Hr,"m",ls).call(this));else{try{await this.cameraManager.open(),Ze(this,Zr,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=ms.allowBeep?"":"none"),a&&(a.style.display=ms.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=ms.allowVibrate?"":"none"),l&&(l.style.display=ms.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const E=()=>{ms.allowBeep=!ms.allowBeep,o&&(o.style.display=ms.allowBeep?"":"none"),a&&(a.style.display=ms.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",E);const C=()=>{ms.allowVibrate=!ms.allowVibrate,h&&(h.style.display=ms.allowVibrate?"":"none"),l&&(l.style.display=ms.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",C);const S=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==qe?void 0:qe.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",E);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",C);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return Ze(this,qr,"open","f"),e&&(e._innerComponent.style.display="",Ke(this,Hr,"m",ls).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),Ke(this,Kr,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Ke(this,Hr,"m",ls).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ze(this,qr,"closed","f"),Ke(this,as,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Ke(this,Hr,"m",ls).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Ke(this,Kr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Ke(this,Hr,"m",ls).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch(()=>{});const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),this.toggleMirroring(this._isEnableMirroring),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ke(this,Kr,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Ke(this,Kr,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(v.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Es._onLog)||void 0===t||t.call(Es,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Ke(this,Hr,"m",ls).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Ke(this,os,"f").minValue=t.min,Ke(this,os,"f").maxValue=t.max}getAutoZoomRange(){return{min:Ke(this,os,"f").minValue,max:Ke(this,os,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=kt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==jt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ai.EF_ENHANCED_FOCUS&&(Ke(this,ss,"f").enhancedFocus=!0),t&ai.EF_AUTO_ZOOM&&(Ke(this,ss,"f").autoZoom=!0),t&ai.EF_TAP_TO_FOCUS&&(Ke(this,ss,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ai.EF_ENHANCED_FOCUS&&(Ke(this,ss,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&ai.EF_AUTO_ZOOM&&(Ke(this,ss,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&ai.EF_TAP_TO_FOCUS&&(Ke(this,ss,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Ke(this,Hr,"m",us).call(this)&&Ke(this,Hr,"m",cs).call(this)||Ke(this,as,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!R(t)&&!P(t))throw TypeError("Invalid 'region'.");Ze(this,es,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Ke(this,es,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ze(this,ts,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Ke(this,Hr,"m",ls).call(this))}startFetching(){if(Ke(this,Hr,"m",ls).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Ke(this,ns,"f")||(Ze(this,ns,!0,"f"),Ke(this,Hr,"m",ds).call(this))}stopFetching(){Ke(this,ns,"f")&&(Es._onLog&&Es._onLog("DCE: stop fetching loop: "+Date.now()),Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),Ze(this,ns,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(Ke(this,Hr,"m",ls).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i;if(i=ji.convert(Ke(this,es,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y);const n=this.cameraView.regionMaskLineWidth;let r;r=Ke(this,es,"f")&&!t?{sx:i.x+n,sy:i.y+n,sWidth:i.width-2*n,sHeight:i.height-2*n,dWidth:i.width-2*n,dHeight:i.height-2*n}:{sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};const s=Math.max(r.dWidth,r.dHeight);if(this.canvasSizeLimit&&s>this.canvasSizeLimit){const t=this.canvasSizeLimit/s;r.dWidth>r.dHeight?(r.dWidth=this.canvasSizeLimit,r.dHeight=Math.round(r.dHeight*t)):(r.dWidth=Math.round(r.dWidth*t),r.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:r,pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?hi.GREY:hi.RGBA,isEnableMirroring:this._isEnableMirroring});if(!o)return null;let a;a=o.pixelFormat===hi.GREY?o.width:4*o.width;let h=!0;return 0===r.sx&&0===r.sy&&r.sWidth===e.width&&r.sHeight===e.height&&(h=!1),{bytes:o.data,width:o.width,height:o.height,stride:a,format:ps.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:ft.ITT_VIDEO_FRAME,isCropped:h,cropRegion:{left:r.sx,top:r.sy,right:r.sx+r.sWidth,bottom:r.sy+r.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:Ke(this,Qr,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Ke(this,ns,"f")&&(Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),Ze(this,rs,setTimeout(()=>{this.disposed||Ke(this,Hr,"m",ds).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ze(this,is,t,"f")}getPixelFormat(){return Ke(this,is,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Ke(this,Hr,"m",ls).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",()=>{t&&this.open(),e.remove()},{once:!0})}),e.addEventListener("change",async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=ji.convert(Ke(this,es,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=Ke(this,$r,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Ke(this,Hr,"m",fs).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Ke(this,Hr,"m",fs).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Ke(this,es,"f"))return JSON.parse(JSON.stringify(t));if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});Ze(this,Zr,t||Ke(this,Zr,"f"),"f")}let e,i,n=Ke(this,es,"f").left||Ke(this,es,"f").x||0,r=Ke(this,es,"f").top||Ke(this,es,"f").y||0;if(!Ke(this,es,"f").isMeasuredInPercentage)return{x:t.x-(n+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").x),y:t.y-(r+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").y)};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ke(this,Hr,"m",ls).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ke(this,Hr,"m",ls).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Ke(this,Hr,"m",ls).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else e=Ke(this,Zr,"f").width,i=Ke(this,Zr,"f").height;return{x:t.x-(Math.round(n*e/100)+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").x),y:t.y-(Math.round(r*i/100)+this.cameraView.regionMaskLineWidth+Ke(this,Zr,"f").y)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Ze(this,hs,!0,"f")}}var Cs,Ss,bs,Ts,Is,xs,Os,Rs;Xr=Es,qr=new WeakMap,Kr=new WeakMap,Zr=new WeakMap,Jr=new WeakMap,$r=new WeakMap,Qr=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,Hr=new WeakSet,ls=function(){return"disabled"!==this.singleFrameMode},cs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},us=function(){for(let t in Ke(this,ss,"f"))if(1==Ke(this,ss,"f")[t])return!0;return!1},ds=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Ke(this,ns,"f"))return Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),void Ze(this,rs,setTimeout(()=>{this.disposed||Ke(this,Hr,"m",t).call(this)},this.fetchInterval),"f");const e=()=>{var t;let e;Es._onLog&&Es._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Ke(this,ts,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=Ke(this,ts,"f"))||void 0===t||t.onErrorReceived(ct.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),Es._onLog&&Es._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Ke(this,Kr,"f").fire("frameAddedToBuffer",null,{async:!1})):Es._onLog&&Es._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:e()}else e();Ke(this,rs,"f")&&clearTimeout(Ke(this,rs,"f")),Ze(this,rs,setTimeout(()=>{this.disposed||Ke(this,Hr,"m",t).call(this)},this.fetchInterval),"f")},fs=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Ke(this,Hr,"m",ls).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Ke(this,Hr,"m",ls).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(Ke(this,Hr,"m",ls).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(Ke(this,Ts,"f")||Ze(this,Ts,new As,"f"),!Ke(this,Ts,"f").magnifierCanvas)return;document.body.contains(Ke(this,Ts,"f").magnifierCanvas)||(Ke(this,Ts,"f").magnifierCanvas.style.position="fixed",Ke(this,Ts,"f").magnifierCanvas.style.boxSizing="content-box",Ke(this,Ts,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Ke(this,Ts,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Ke(this,xs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Ke(this,Ts,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Ke(this,Ts,"f").magnifierCanvas.style.left="auto",Ke(this,Ts,"f").magnifierCanvas.style.top="0",Ke(this,Ts,"f").magnifierCanvas.style.right="0"):(Ke(this,Ts,"f").magnifierCanvas.style.left="0",Ke(this,Ts,"f").magnifierCanvas.style.top="0",Ke(this,Ts,"f").magnifierCanvas.style.right="auto")}Ke(this,Ts,"f").show()}),xs.set(this,()=>{Ke(this,Ts,"f")&&Ke(this,Ts,"f").hide()}),Os.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Xi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(O(t)){Ze(this,bs,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===v.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2})),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new li.Control({positionHandler:Ti,actionHandler:Oi(i>0?i-1:n,xi),actionName:"modifyPolygon",pointIndex:i}),t},{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=li.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Ke(this,Li,"f")&&this.setLine(Ke(this,Li,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!D(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ze(this,Li,JSON.parse(JSON.stringify(t)),"f")}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Ke(this,Li,"f")?JSON.parse(JSON.stringify(Ke(this,Li,"f"))):null}},QuadDrawingItem:Fi,RectDrawingItem:bi,TextDrawingItem:Di});const Ms="undefined"==typeof self,Fs=Ms?{}:self,Ps="function"==typeof importScripts,ks=(()=>{if(!Ps){if(!Ms&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Ns=t=>t&&"object"==typeof t&&"function"==typeof t.then,Bs=(async()=>{})().constructor;let js=class extends Bs{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Ns(t)?e=t:"function"==typeof t&&(e=new Bs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Ns(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Us=" is not allowed to change after `createInstance` or `loadWasm` is called.",Vs=!Ms&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",Gs=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Us);i._license=e}};!Ms&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ws=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Ws(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Us);i._licenseServer=e}},Hs=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Us);i._deviceFriendlyName=e}};let Xs,zs,qs,Ks,Zs;"undefined"!=typeof navigator&&(Xs=navigator,zs=Xs.userAgent,qs=Xs.platform,Ks=Xs.mediaDevices),function(){if(!Ms){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Xs.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:qs,search:"Win"},Mac:{str:qs},Linux:{str:qs}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||zs,o=r.search||e,a=r.verStr||zs,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||zs,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=zs.indexOf("Windows NT")&&(r="HarmonyOS"),Zs={browser:i,version:n,OS:r}}Ms&&(Zs={browser:"ssr",version:0,OS:"ssr"})}(),Ks&&Ks.getUserMedia,"Chrome"===Zs.browser&&Zs.version>66||"Safari"===Zs.browser&&Zs.version>13||"OPR"===Zs.browser&&Zs.version>43||"Edge"===Zs.browser&&Zs.version;const Js=()=>(jt.loadWasm(),It("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Ws(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Fs.crypto||(s="Please upgrade your browser to support online key."),Fs.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Us)})(Qs),o=new js;Qs._pLoad.task=o,(async()=>{try{await Qs._pLoad}catch(t){}})();let a=Rt();At[a]=e=>{if(e.message&&Qs._onAuthMessage){let t=Qs._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(Dt&&Dt("init license success"),e.message&&console.warn(e.message),jt._bSupportIRTModule=e.bSupportIRTModule,jt._bSupportDce4Module=e.bSupportDce4Module,Qs.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=B(jt.engineResourcePaths),i=("DCV"===jt._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Qs._bNeverShowDialog,engineResourcePath:i,_onLog:Dt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await Tt("core"),xt.postMessage({type:"license_dynamsoft",body:{v:"4.0.60-dev-20250812170103",brtk:!!t,bptk:1===t,l:e,os:Zs,fn:Qs.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),Qs.bCallInitLicense=!0,await o}));let $s;kt.license={},kt.license.dynamsoft=Js,kt.license.getAR=async()=>{{let t=bt.dynamsoft_inited;t&&t.isRejected&&await t}return xt?new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success){delete i.success;{let t=Qs.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},xt.postMessage({type:"license_getAR",id:i})}):null};let Qs=class t{static setLicenseServer(e){Ys(t,e)}static get license(){return this._license}static set license(e){Gs(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Ys(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Hs(t,e)}static initLicense(e,i){if(Gs(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Js()}static setDeviceFriendlyName(e){Hs(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await It("dynamsoft_uuid",async()=>{await jt.loadWasm();let t=new js,e=Rt();At[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},xt.postMessage({type:"license_getDeviceUUID",id:e}),$s=await t}),$s))()}};Qs._pLoad=new js,Qs.bPassValidation=!1,Qs.bCallInitLicense=!1,Qs._license=Vs,Qs._licenseServer=[],Qs._deviceFriendlyName="",jt.engineResourcePaths.license={version:"4.0.60-dev-20250812170103",path:ks,isInternal:!0},Nt.license={wasm:!0,js:!0},kt.license.LicenseManager=Qs;const to="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,to)<0&&(jt.engineResourcePaths.std={version:to,path:(t=>{if(null==t&&(t="./"),Ms||Ps);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(ks+`../../dynamsoft-capture-vision-std@${to}/dist/`),isInternal:!0});var eo=Object.freeze({__proto__:null,LicenseManager:Qs,LicenseModule:class{static getVersion(){return`4.0.60-dev-20250812170103(Worker: ${Pt.license&&Pt.license.worker||"Not Loaded"}, Wasm: ${Pt.license&&Pt.license.wasm||"Not Loaded"})`}}});const io=()=>window.matchMedia("(orientation: landscape)").matches,no=t=>Object.prototype.toString.call(t).slice(8,-1);function ro(t,e){for(const i in e)"Object"===no(e[i])&&i in t?ro(t[i],e[i]):t[i]=e[i];return t}function so(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function oo(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;ie.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const ho="undefined"==typeof self,lo="function"==typeof importScripts,co=(()=>{if(!lo){if(!ho&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),uo=t=>{if(null==t&&(t="./"),ho||lo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};jt.engineResourcePaths.utility={version:"2.0.60-dev-20250812170132",path:co,isInternal:!0},Nt.utility={js:!0,wasm:!0};const fo="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,fo)<0&&(jt.engineResourcePaths.std={version:fo,path:uo(co+`../../dynamsoft-capture-vision-std@${fo}/dist/`),isInternal:!0});const go="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,go)<0)&&(jt.engineResourcePaths.dip={version:go,path:uo(co+`../../dynamsoft-image-processing@${go}/dist/`),isInternal:!0});function mo(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const po="undefined"==typeof self,_o="function"==typeof importScripts,vo=(()=>{if(!_o){if(!po&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),yo=t=>{if(null==t&&(t="./"),po||_o);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};jt.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:vo,isInternal:!0},Nt.dbr={js:!1,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},kt.dbr={};const wo="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,wo)<0&&(jt.engineResourcePaths.std={version:wo,path:yo(vo+`../../dynamsoft-capture-vision-std@${wo}/dist/`),isInternal:!0});const Eo="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,Eo)<0)&&(jt.engineResourcePaths.dip={version:Eo,path:yo(vo+`../../dynamsoft-image-processing@${Eo}/dist/`),isInternal:!0});const Co={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var So,bo,To,Io,xo,Oo,Ro,Ao,Do,Lo;function Mo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function ko(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function jo(t){let e=0;for(let i=0;i0}function Vo(t,e){for(let i=0;i<4;i++)if(!Uo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}(xo=So||(So={}))[xo.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",xo[xo.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",xo[xo.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(bo||(bo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(To||(To={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(Io||(Io={}));function Go(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=ko(r)[3],h=ko(r)[1],l=ko(s)[3],c=ko(s)[1];let u,d=0;if(u=Math.max(Math.abs(Po(a,e.points[0])),Math.abs(Po(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(h,e.points[1])),Math.abs(Po(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Po(l,t.points[0])),Math.abs(Po(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(c,t.points[1])),Math.abs(Po(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=No(ko(r)[0]),g=No(ko(r)[2]),m=No(ko(s)[0]),p=No(ko(s)[2]),_=Fo(f,p),v=Fo(m,g),y=_>v,w=Math.min(_,v),E=Fo(f,g),C=Fo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,E),S=Math.min(S,C),!!(w{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Vo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Vo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Vo(t,this.location.points[e]))return!0;if(Vo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Po(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Bo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{Mo(e,t)&&i.push(t)}),e.forEach(e=>{Mo(t,e)&&i.push(e)}),jo(function(t){if(t.length<=1)return t;t.sort((t,e)=>t.x-e.x||t.y-e.y);const e=t.shift();return t.sort((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x)),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Yo={barcode:2,text_line:4,detected_quad:8,deskewed_image:16},Ho=t=>Object.values(Yo).includes(t)||Yo.hasOwnProperty(t),Xo=(t,e)=>"string"==typeof t?e[Yo[t]]:e[t],zo=(t,e,i)=>{"string"==typeof t?e[Yo[t]]=i:e[t]=i},qo=(t,e,i)=>{const n=[{type:ht.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:ht.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class Ko{constructor(){this.verificationEnabled={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!0,[ht.CRIT_DETECTED_QUAD]:!0,[ht.CRIT_DESKEWED_IMAGE]:!1},this.duplicateFilterEnabled={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1},this.duplicateForgetTime={[ht.CRIT_BARCODE]:3e3,[ht.CRIT_TEXT_LINE]:3e3,[ht.CRIT_DETECTED_QUAD]:3e3,[ht.CRIT_DESKEWED_IMAGE]:3e3},this.latestOverlappingEnabled={[ht.CRIT_BARCODE]:!1,[ht.CRIT_TEXT_LINE]:!1,[ht.CRIT_DETECTED_QUAD]:!1,[ht.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[ht.CRIT_BARCODE]:5,[ht.CRIT_TEXT_LINE]:5,[ht.CRIT_DETECTED_QUAD]:5,[ht.CRIT_DESKEWED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,Oo.set(this,new Map),Ro.set(this,new Map),Ao.set(this,new Map),Do.set(this,new Map),Lo.set(this,new Map),Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),qo(this,t,ht.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{qo(this,t,ht.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){mo(this,Oo,"f").forEach((t,e)=>{zo(e,this.verificationEnabled,t)}),mo(this,Ro,"f").forEach((t,e)=>{zo(e,this.duplicateFilterEnabled,t)}),mo(this,Ao,"f").forEach((t,e)=>{zo(e,this.duplicateForgetTime,t)}),mo(this,Do,"f").forEach((t,e)=>{zo(e,this.latestOverlappingEnabled,t)}),mo(this,Lo,"f").forEach((t,e)=>{zo(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){Ho(t)&&mo(this,Oo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Ho(t)&&Xo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Ho(t)&&(e&&this.enableLatestOverlapping(t,!1),mo(this,Ro,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Ho(t)&&Xo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Ho(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),mo(this,Ao,"f").set(t,e))}getDuplicateForgetTime(t){return Ho(t)?Xo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Ho(t)&&mo(this,Lo,"f").set(t,e)}getMaxOverlappingFrames(t){return Ho(t)?Xo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Ho(t)&&(e&&this.enableResultDeduplication(t,!1),mo(this,Do,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Ho(t)&&Xo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[ht.CRIT_BARCODE,ht.CRIT_TEXT_LINE,ht.CRIT_DETECTED_QUAD,ht.CRIT_DESKEWED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0);return new Wo(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Co.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Co.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}f.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),d.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}Oo=new WeakMap,Ro=new WeakMap,Ao=new WeakMap,Do=new WeakMap,Lo=new WeakMap;const Zo=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:v.IPF_ABGR_8888}};var Jo,$o,Qo,ta;class ea{async readFromFile(t){return await Zo(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=G(t);return j(n,e,i)}async readFromMemory(t){if(!mo(ea,Jo,"f",$o).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=mo(ea,Jo,"f",$o).get(t);return await new Promise((t,n)=>{let r=Rt();At[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},xt.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{var i,n;if(e.success)return function(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");r?r.value=i:e.set(t,i)}(i=ea,Jo,(n=mo(i,Jo,"f",Qo),++n),0,Qo),mo(ea,Jo,"f",$o).set(mo(ea,Jo,"f",Qo),JSON.parse(e.memery)),t(mo(ea,Jo,"f",Qo));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}Jo=ea,$o={value:new Map},Qo={value:0};!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(ta||(ta={}));var ia,na,ra,sa,oa,aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ea,Ca,Sa,ba,Ta,Ia,xa,Oa=Object.freeze({__proto__:null,get EnumFilterType(){return ta},ImageDrawer:class{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await Zo(t);else if("string"==typeof t){let e=await k(t,"blob");a=await Zo(e)}else O(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=Rt();At[l]=async e=>{if(e.success)return o&&(new ea).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},xt.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}},ImageIO:ea,ImageProcessor:class{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await Zo(t);return await new Promise((t,l)=>{let c=Rt();At[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},xt.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await Zo(t);return await new Promise((t,h)=>{let l=Rt();At[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},xt.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await Zo(t);return await new Promise((t,l)=>{let c=Rt();At[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},xt.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Zo(t);return await new Promise((t,a)=>{let h=Rt();At[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},xt.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}},MultiFrameResultCrossFilter:Ko,UtilityModule:class{static getVersion(){return`2.0.60-dev-20250812170132(Worker: ${Pt.utility&&Pt.utility.worker||"Not Loaded"}, Wasm: ${Pt.utility&&Pt.utility.wasm||"Not Loaded"})`}}});class Ra{constructor(e){if(ia.add(this),sa.set(this,void 0),oa.set(this,{status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]}),aa.set(this,!1),ha.set(this,void 0),la.set(this,void 0),ca.set(this,void 0),ua.set(this,void 0),this.config=oo(Vt),e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";ro(this.config,e),Es._isRTU=!0}get disposed(){return i(this,aa,"f")}launch(){return e(this,void 0,void 0,function*(){if(i(this,aa,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(i(Ra,na,"f",ra)&&!i(Ra,na,"f",ra).isFulfilled&&!i(Ra,na,"f",ra).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return n(Ra,na,new Yt,"f",ra),yield i(this,ia,"m",da).call(this),i(Ra,na,"f",ra)})}decode(t,r="ReadBarcodes_Default"){return e(this,void 0,void 0,function*(){n(this,la,r,"f"),yield i(this,ia,"m",fa).call(this,!0),i(this,ua,"f")||n(this,ua,new Ko,"f"),i(this,ua,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(i(this,ua,"f"));const e=new Be;e.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(e);const s=yield this._cvRouter.capture(t,r);return i(this,ua,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(i(this,ua,"f")),this._cvRouter.removeResultReceiver(e),s})}dispose(){var t,e,r,s,o,a,h;n(this,aa,!0,"f"),i(Ra,na,"f",ra)&&i(Ra,na,"f",ra).isPending&&i(Ra,na,"f",ra).resolve(i(this,oa,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(e=this._cameraView)||void 0===e||e.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",i(this,sa,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}na=Ra,sa=new WeakMap,oa=new WeakMap,aa=new WeakMap,ha=new WeakMap,la=new WeakMap,ca=new WeakMap,ua=new WeakMap,ia=new WeakSet,da=function(){return e(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield i(this,ia,"m",fa).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),so(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){i(this,ia,"m",ba).call(this),i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(i(this,la,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(e){i(this,oa,"f").status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(Ra,na,"f",ra).reject(new Error(i(this,oa,"f").status.message)),this.dispose()}finally{i(this,ia,"m",Ia).call(this,"Loading...",!1)}})},fa=function(r=!1){return e(this,void 0,void 0,function*(){if(jt.engineResourcePaths=this.config.engineResourcePaths,!r){const e=B(jt.engineResourcePaths);if(this._cameraView=yield Or.createInstance(e.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),this._cameraEnhancer=yield Es.createInstance(this._cameraView),this.disposed)return;if(yield i(this,ia,"m",ma).call(this),this.disposed)return;if(this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1),n(this,ca,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}}yield Qs.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield Ne.createInstance()),this.disposed||(this.config.scanMode!==t.EnumScanMode.SM_SINGLE||r?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{i(Ra,na,"f",ra).reject(new Error(t.message)),this.dispose()},yield i(this,ia,"m",ga).call(this,r),this.disposed||r||(this._cvRouter.setInput(this._cameraEnhancer),i(this,ia,"m",pa).call(this),yield i(this,ia,"m",_a).call(this),this.disposed)))})},ga=function(r=!1){return e(this,void 0,void 0,function*(){if(r||(this.config.scanMode===t.EnumScanMode.SM_SINGLE?n(this,la,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&n(this,la,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const e=yield this._cvRouter.getSimplifiedSettings(i(this,la,"f"));if(this.disposed)return;r||this.config.scanMode!==t.EnumScanMode.SM_SINGLE||(e.outputOriginalImage=!0);let s=this.config.barcodeFormats;if(s){Array.isArray(s)||(s=[s]),e.barcodeSettings.barcodeFormatIds=BigInt(0);for(let t=0;t{document.head.appendChild(t.cloneNode(!0))}),n(this,ha,p.querySelector(".result-item"),"f");const y=p.querySelector(".btn-clear");if(y&&(y.addEventListener("click",()=>{i(this,oa,"f").barcodeResults=[],i(this,ia,"m",Ca).call(this)}),null===(o=null===(s=null===(r=this.config)||void 0===r?void 0:r.resultViewConfig)||void 0===s?void 0:s.toolbarButtonsConfig)||void 0===o?void 0:o.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;y.style.display=t.isHidden?"none":"flex",y.className=t.className?t.className:"btn-clear",y.innerText=t.label?t.label:"Clear",t.isHidden&&(p.querySelector(".toolbar-btns").style.justifyContent="center")}const w=p.querySelector(".btn-done");if(w&&(w.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(c=null===(l=null===(h=this.config)||void 0===h?void 0:h.resultViewConfig)||void 0===l?void 0:l.toolbarButtonsConfig)||void 0===c?void 0:c.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;w.style.display=t.isHidden?"none":"flex",w.className=t.className?t.className:"btn-done",w.innerText=t.label?t.label:"Done",t.isHidden&&(p.querySelector(".toolbar-btns").style.justifyContent="center")}if(null===(d=null===(u=this.config)||void 0===u?void 0:u.scannerViewConfig)||void 0===d?void 0:d.showCloseButton){const e=p.querySelector(".btn-close");e&&(e.style.display="",e.addEventListener("click",()=>{i(this,oa,"f").barcodeResults=[],i(this,oa,"f").status={code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}if(null===(f=this.config)||void 0===f?void 0:f.scannerViewConfig.showFlashButton){const t=p.querySelector(".btn-flash-auto"),n=p.querySelector(".btn-flash-open"),r=p.querySelector(".btn-flash-close");if(t){t.style.display="";let s=null,o=250,a=20,h=3;const l=(l=250)=>e(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==s){if(!(le(this,void 0,void 0,function*(){var e;if(i(this,aa,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(s),void(s=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(s),s=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(v.IPF_GRAYSCALED===l.format){for(let t=0;t=h){null===(e=Es._onLog)||void 0===e||e.call(Es,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,t.style.display="none",n.style.display="",r.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});s=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),t.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),t.style.display="none",n.style.display="",r.style.display="none"})),n.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),t.style.display="none",n.style.display="none",r.style.display=""})),r.addEventListener("click",()=>e(this,void 0,void 0,function*(){l(1e3),t.style.display="",n.style.display="none",r.style.display="none"}))}}let E=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(E)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const t=p.querySelector(".camera-control");if(t){t.style.display="";const n=yield this._cameraEnhancer.getAllCameras(),r=this.config.scannerViewConfig.cameraSwitchControl,s=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px"}),e},o=()=>{if(0===n.length)return null;if("listAll"===r){const t=p.querySelector(".camera-list");for(let e of n){const i=s(e);t.append(i)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const r=t=>{for(let e of o)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};t.addEventListener("click",t=>e(this,void 0,void 0,function*(){const e=t.target;i(this,ia,"m",Ia).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:e.deviceId,label:e.label,_checked:e._checked});const n=this._cameraEnhancer.getSelectedCamera(),s=this._cameraEnhancer.getCapabilities();so(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(s.torch?i(this,ia,"m",Ta).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),r(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(i(this,la,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),i(this,ia,"m",Ia).call(this,"Loading...",!1)}));const o=p.querySelectorAll(".camera-list div");return()=>e(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();r(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===r?()=>e(this,void 0,void 0,function*(){i(this,ia,"m",Ia).call(this,"Accessing Camera...",!0);const t=so(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&i(this,ia,"m",Ta).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&i(this,ia,"m",Ta).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),i(this,ia,"m",Ia).call(this,"Loading...",!1)}):void 0},a=o();t.addEventListener("click",t=>e(this,void 0,void 0,function*(){t.stopPropagation(),a&&(yield a())}))}}this.config.showUploadImageButton&&i(this,ia,"m",ba).call(this,p.querySelector(".btn-upload-image"));const C=this._cameraView.getUIElement();C.shadowRoot.querySelector(".dce-sel-camera").remove(),C.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const S=p.querySelector(".barcode-scanner-container");S.style.display=io()?"flex":"",this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this.config.showResultView=!1);const b=this.config.showResultView;let T;if(this.config.container?(S.style.position="relative",T=this.config.container):T=document.body,"string"==typeof T&&(T=document.querySelector(T),null===T))throw new Error("Failed to get the container");let I=this.config.scannerViewConfig.container;if("string"==typeof I&&(I=document.querySelector(I),null===I))throw new Error("Failed to get the container of the scanner view.");let x=this.config.resultViewConfig.container;if("string"==typeof x&&(x=document.querySelector(x),null===x))throw new Error("Failed to get the container of the result view.");const O=p.querySelector(".scanner-view-container"),R=p.querySelector(".result-view-container"),A=p.querySelector(".loading-page");O.append(A),I&&(O.append(C),I.append(O)),x&&x.append(R),I||x?I&&!x?(this.config.container||(R.style.position="absolute"),x=R,T.append(R)):!I&&x&&(this.config.container||(O.style.position="absolute"),I=O,O.append(C),T.append(O)):(I=O,x=R,b&&(Object.assign(O.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"}),Object.assign(R.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"})),O.append(C),T.append(S)),document.querySelector(".result-view-container").style.display=b?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),n(this,sa,()=>{Object.assign(S.style,{display:io()?"flex":""}),!b||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(I.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"}),Object.assign(x.style,{width:io()?"50%":"100%",height:io()?"100%":"50%"}))},"f"),window.addEventListener("resize",i(this,sa,"f")),this._cameraView._createDrawingLayer(2)})},pa=function(){const n=new Be;n.onCapturedResultReceived=n=>e(this,void 0,void 0,function*(){if(i(this,ca,"f")&&i(this,ca,"f").clearDrawingItems(),n.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of n.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));i(this,ca,"f").addDrawingItems(t)}this.config.scanMode===t.EnumScanMode.SM_SINGLE?i(this,ia,"m",va).call(this,n):i(this,ia,"m",ya).call(this,n)}}),this._cvRouter.addResultReceiver(n)},_a=function(){return e(this,void 0,void 0,function*(){i(this,ua,"f")||n(this,ua,new Ko,"f"),i(this,ua,"f").enableResultCrossVerification(2,!0),i(this,ua,"f").enableResultDeduplication(2,!0),i(this,ua,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(i(this,ua,"f")),i(this,ua,"f").isResultCrossVerificationEnabled=()=>!1,i(this,ua,"f").isResultDeduplicationEnabled=()=>!1})},va=function(e){const n=this._cameraView.getUIElement().shadowRoot;let r=new Promise(t=>{if(e.decodedBarcodesResult.barcodeResultItems.length>1){i(this,ia,"m",Ea).call(this);for(let i of e.decodedBarcodesResult.barcodeResultItems){let e=0,r=0;for(let t=0;t<4;++t){let n=i.location.points[t];e+=n.x,r+=n.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{t(i)}),n.append(o)}}else t(e.decodedBarcodesResult.barcodeResultItems[0])});r.then(n=>{const r=e.items.filter(t=>t.type===ht.CRIT_ORIGINAL_IMAGE)[0].imageData,s={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},originalImageResult:r,barcodeImage:(()=>{const t=U(r),e=n.location.points,i=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-i,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-i,e[0].y-s);for(let t=1;t`${t.formatString}_${t.text}`==`${e.formatString}_${e.text}`);-1===t?(e.count=1,i(this,oa,"f").barcodeResults.unshift(e),i(this,ia,"m",Ca).call(this,e)):(i(this,oa,"f").barcodeResults[t].count++,i(this,ia,"m",Sa).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(e)}},wa=function(t){const e=i(this,ha,"f").cloneNode(!0);e.querySelector(".format-string").innerText=t.formatString;e.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),e.id=`${t.formatString}_${t.text}`;return e.querySelector(".delete-icon").addEventListener("click",()=>{const e=[...document.querySelectorAll(".main-list .result-item")],n=e.findIndex(e=>e.id===`${t.formatString}_${t.text}`);i(this,oa,"f").barcodeResults.splice(n,1),e[n].remove(),0===i(this,oa,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),e},Ea=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Ca=function(e){if(!this.config.showResultView)return;const n=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==t.EnumScanMode.SM_SINGLE))return;const r=document.querySelector(".main-list");if(!e)return r.textContent="",void(this.config.showPoweredByDynamsoft&&(n.style.display=""));n.style.display="none";const s=i(this,ia,"m",wa).call(this,e);r.insertBefore(s,document.querySelector(".result-item"))},Sa=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},ba=function(n){n||(n=document.querySelector(".btn-upload-image")),n&&(n.style.display="",n.onchange=n=>e(this,void 0,void 0,function*(){const e=n.target.files,r={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]};let s=0;i(this,ia,"m",Ia).call(this,`Capturing... [${s}/${e.length}]`,!0);let o=!1;for(let t=0;t`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===e?(t.count=1,i(this,oa,"f").barcodeResults.unshift(t),i(this,ia,"m",Ca).call(this,t)):(i(this,oa,"f").barcodeResults[e].count++,i(this,ia,"m",Sa).call(this,e))}else if(o.decodedBarcodesResult.barcodeResultItems)for(let t of o.decodedBarcodesResult.barcodeResultItems){const e=r.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,r.barcodeResults.push(t))}i(this,ia,"m",Ia).call(this,`Capturing... [${++s}/${e.length}]`,!0)}catch(e){r.status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(Ra,na,"f",ra).reject(new Error(r.status.message)),this.dispose()}i(this,ia,"m",Ia).call(this,"Loading...",!1),this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(i(Ra,na,"f",ra).resolve(r),this.dispose()),n.target.value=""}))},Ta=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},Ia=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},xa=function(t){let e=Rt();At[e]=()=>{},xt.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},ra={value:null};const Aa="undefined"==typeof self,Da="function"==typeof importScripts,La=(()=>{if(!Da){if(!Aa&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Ma=t=>{if(null==t&&(t="./"),Aa||Da);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};jt.engineResourcePaths.dbr={version:"11.0.60-dev-20250812165905",path:La,isInternal:!0},Nt.dbr={js:!1,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE,Ct.MN_DYNAMSOFT_IMAGE_PROCESSING]},kt.dbr={};const Fa="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,Fa)<0&&(jt.engineResourcePaths.std={version:Fa,path:Ma(La+`../../dynamsoft-capture-vision-std@${Fa}/dist/`),isInternal:!0});const Pa="3.0.10";(!jt.engineResourcePaths.dip||"string"!=typeof jt.engineResourcePaths.dip&&N(jt.engineResourcePaths.dip.version,Pa)<0)&&(jt.engineResourcePaths.dip={version:Pa,path:Ma(La+`../../dynamsoft-image-processing@${Pa}/dist/`),isInternal:!0});const ka={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Na,Ba,ja,Ua;!function(t){t[t.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",t[t.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",t[t.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(Na||(Na={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Ba||(Ba={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(ja||(ja={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(Ua||(Ua={}));var Va,Ga,Wa=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=Pt.dbr&&Pt.dbr.wasm;return`11.0.60-dev-20250812165905(Worker: ${Pt.dbr&&Pt.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:ka,get EnumDeblurMode(){return Ua},get EnumExtendedBarcodeResultType(){return Na},get EnumLocalizationMode(){return ja},get EnumQRCodeErrorCorrectionLevel(){return Ba}});function Ya(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Ha(e,t,"map"),t.getFieldRawValue=t=>Ha(e,t,"raw"),t.getFieldMappingStatus=t=>Xa(e,t),t.getFieldValidationStatus=t=>za(e,t),delete t.fullCodeString}function Ha(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=Ha(r,e,i);if(void 0!==t)return t}}}function Xa(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Va[i.MappingStatus]):Va.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=Xa(n,e);if(void 0!==t)return t}}}function za(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(Ga[i.ValidationStatus]):Ga.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=za(n,e);if(void 0!==t)return t}}}function qa(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(Va||(Va={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(Ga||(Ga={}));const Ka=t=>t&&"object"==typeof t&&"function"==typeof t.then,Za=(async()=>{})().constructor;class Ja extends Za{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Ka(t)?e=t:"function"==typeof t&&(e=new Za(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Ka(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class $a{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!kt.license)throw Error("Module `license` is not existed.");await kt.license.dynamsoft(),await jt.loadWasm();const t=new $a,e=new Ja;let i=Rt();return At[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},xt.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){qa(this);let t=Rt();this.bDestroyed=!0,At[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},xt.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(qa(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await k(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Rt();At[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},xt.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return qa(this),await new Promise((t,e)=>{let i=Rt();At[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},xt.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(qa(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise((i,n)=>{let r=Rt();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(Ya(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},xt.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const Qa="undefined"==typeof self,th="function"==typeof importScripts,eh=(()=>{if(!th){if(!Qa&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();jt.engineResourcePaths.dcp={version:"3.0.60-dev-20250812165958",path:eh,isInternal:!0},Nt.dcp={js:!0,wasm:!0,deps:[Ct.MN_DYNAMSOFT_LICENSE]},kt.dcp={handleParsedResultItem:Ya};const ih="2.0.0";"string"!=typeof jt.engineResourcePaths.std&&N(jt.engineResourcePaths.std.version,ih)<0&&(jt.engineResourcePaths.std={version:ih,path:(t=>{if(null==t&&(t="./"),Qa||th);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(eh+`../../dynamsoft-capture-vision-std@${ih}/dist/`),isInternal:!0});var nh=Object.freeze({__proto__:null,CodeParser:$a,CodeParserModule:class{static getVersion(){const t=Pt.dcp&&Pt.dcp.wasm;return`3.0.60-dev-20250812165958(Worker: ${Pt.dcp&&Pt.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await jt.loadWasm(),await new Promise((i,n)=>{let r=Rt();At[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],o=B(jt.engineResourcePaths);xt.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===jt._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}},get EnumMappingStatus(){return Va},get EnumValidationStatus(){return Ga}});jt._bundleEnv="DBR",Ne._defaultTemplate="ReadSingleBarcode",jt.engineResourcePaths.dbrBundle={version:"11.0.6000",path:o,isInternal:!0},t.BarcodeScanner=Ra,t.CVR=Ue,t.Core=Ut,t.DBR=Wa,t.DCE=Ls,t.DCP=nh,t.License=eo,t.Utility=Oa}); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{})}(this,function(t){"use strict";function e(t,e,i,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function i(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function n(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const r="undefined"==typeof self,s="function"==typeof importScripts,o=(()=>{if(!s){if(!r&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),a=t=>{if(null==t&&(t="./"),r||s);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var h,l,c;t.EnumScanMode=void 0,(h=t.EnumScanMode||(t.EnumScanMode={}))[h.SM_SINGLE=0]="SM_SINGLE",h[h.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE",t.EnumOptimizationMode=void 0,(l=t.EnumOptimizationMode||(t.EnumOptimizationMode={}))[l.OM_NONE=0]="OM_NONE",l[l.OM_SPEED=1]="OM_SPEED",l[l.OM_COVERAGE=2]="OM_COVERAGE",l[l.OM_BALANCE=3]="OM_BALANCE",l[l.OM_DPM=4]="OM_DPM",l[l.OM_DENSE=5]="OM_DENSE",t.EnumResultStatus=void 0,(c=t.EnumResultStatus||(t.EnumResultStatus={}))[c.RS_SUCCESS=0]="RS_SUCCESS",c[c.RS_CANCELLED=1]="RS_CANCELLED",c[c.RS_FAILED=2]="RS_FAILED";const u=t=>t&&"object"==typeof t&&"function"==typeof t.then,d=(async()=>{})().constructor;let f=class extends d{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,u(t)?e=t:"function"==typeof t&&(e=new d(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(u(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function g(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function m(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var p,_,v;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(p||(p={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(_||(_={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(v||(v={}));const y="undefined"==typeof self,w="function"==typeof importScripts,E=(()=>{if(!w){if(!y&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),C=t=>{if(null==t&&(t="./"),y||w);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},S=t=>Object.prototype.toString.call(t),b=t=>Array.isArray?Array.isArray(t):"[object Array]"===S(t),T=t=>"number"==typeof t&&!Number.isNaN(t),I=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),x=t=>!(!I(t)||!T(t.width)||t.width<=0||!T(t.height)||t.height<=0||!T(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!A(t.tag)),O=t=>!!x(t)&&t.bytes instanceof Uint8Array,R=t=>!(!I(t)||!T(t.left)||t.left<0||!T(t.top)||t.top<0||!T(t.right)||t.right<0||!T(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),A=t=>null===t||!!I(t)&&!!T(t.imageId)&&"type"in t,D=t=>!(!I(t)||!L(t.startPoint)||!L(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),L=t=>!!I(t)&&!!T(t.x)&&!!T(t.y),M=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),F=t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!L(t)),P=t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.width)||t.width<0||!T(t.height)||t.height<0),k=async(t,e,i)=>await new Promise((n,r)=>{let s=new XMLHttpRequest;s.responseType=e,s.onloadstart=()=>{i&&i.loadstartCallback&&i.loadstartCallback()},s.onloadend=async()=>{i&&i.loadendCallback&&i.loadendCallback(),s.status<200||s.status>=300?r(new Error(t+" "+s.status)):n(s.response)},s.onprogress=t=>{i&&i.progressCallback&&i.progressCallback(t)},s.onerror=()=>{r(new Error("Network Error: "+s.statusText))},s.open("GET",t,!0),s.send()}),N=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${Y[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${Y[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},j=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await G(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),U=t=>{O(t)&&(t=W(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},V=(t,e)=>{O(e)&&(e=W(e));const i=U(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},G=async(t,e)=>{O(e)&&(e=W(e));const i=U(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},W=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===v.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===v.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},Y={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var H,X,z,q,K,Z,J,$;let Q,tt,et,it,nt,rt=class t{get _isFetchingStarted(){return g(this,K,"f")}constructor(){H.add(this),X.set(this,[]),z.set(this,1),q.set(this,p.BOPM_BLOCK),K.set(this,!1),Z.set(this,void 0),J.set(this,_.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!O(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(g(this,X,"f").length>=g(this,z,"f"))switch(g(this,q,"f")){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:if(g(this,X,"f").push(t),I(g(this,Z,"f"))&&T(g(this,Z,"f").imageId)&&1==g(this,Z,"f").keepInBuffer)for(;g(this,X,"f").length>g(this,z,"f");){const t=g(this,X,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==g(this,Z,"f").imageId});g(this,X,"f").splice(t,1)}else g(this,X,"f").splice(0,g(this,X,"f").length-g(this,z,"f"))}else g(this,X,"f").push(t)}getImage(){if(0===g(this,X,"f").length)return null;let e;if(g(this,Z,"f")&&T(g(this,Z,"f").imageId)){const t=g(this,H,"m",$).call(this,g(this,Z,"f").imageId);if(t<0)throw new Error(`Image with id ${g(this,Z,"f").imageId} doesn't exist.`);e=g(this,X,"f").slice(t,t+1)[0]}else e=g(this,X,"f").pop();if([v.IPF_RGB_565,v.IPF_RGB_555,v.IPF_RGB_888,v.IPF_ARGB_8888,v.IPF_RGB_161616,v.IPF_ARGB_16161616,v.IPF_ABGR_8888,v.IPF_ABGR_16161616,v.IPF_BGR_888].includes(e.format)){if(g(this,J,"f")===_.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every(t=>T(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==S(e))throw new TypeError("Invalid 'keepInBuffer'.");m(this,Z,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){m(this,Z,null,"f")}hasImage(t){return g(this,H,"m",$).call(this,t)>=0}startFetching(){m(this,K,!0,"f")}stopFetching(){m(this,K,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(m(this,z,t,"f");g(this,X,"f")&&g(this,X,"f").length>t;)g(this,X,"f").shift()}getMaxImageCount(){return g(this,z,"f")}getImageCount(){return g(this,X,"f").length}clearBuffer(){g(this,X,"f").length=0}isBufferEmpty(){return 0===g(this,X,"f").length}setBufferOverflowProtectionMode(t){m(this,q,t,"f")}getBufferOverflowProtectionMode(){return g(this,q,"f")}setColourChannelUsageType(t){m(this,J,t,"f")}getColourChannelUsageType(){return g(this,J,"f")}};X=new WeakMap,z=new WeakMap,q=new WeakMap,K=new WeakMap,Z=new WeakMap,J=new WeakMap,H=new WeakSet,$=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return g(this,X,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(Q=navigator,tt=Q.userAgent,et=Q.platform,it=Q.mediaDevices),function(){if(!y){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Q.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:et,search:"Win"},Mac:{str:et},Linux:{str:et}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||tt,o=r.search||e,a=r.verStr||tt,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||tt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=tt.indexOf("Windows NT")&&(r="HarmonyOS"),nt={browser:i,version:n,OS:r}}y&&(nt={browser:"ssr",version:0,OS:"ssr"})}();const st="undefined"!=typeof WebAssembly&&tt&&!(/Safari/.test(tt)&&!/Chrome/.test(tt)&&/\(.+\s11_2_([2-6]).*\)/.test(tt)),ot=!("undefined"==typeof Worker),at=!(!it||!it.getUserMedia),ht=async()=>{let t=!1;if(at)try{(await it.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var lt,ct,ut,dt,ft,gt,mt,pt,_t;"Chrome"===nt.browser&&nt.version>66||"Safari"===nt.browser&&nt.version>13||"OPR"===nt.browser&&nt.version>43||"Edge"===nt.browser&&nt.version,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(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_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(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",t[t.GEM_END=-1]="GEM_END"}(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",t[t.GTM_END=-1]="GTM_END"}(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.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(_t||(_t={}));const vt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var yt,wt,Et,Ct,St,bt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(yt||(yt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(wt||(wt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(Et||(Et={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(Ct||(Ct={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(St||(St={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(bt||(bt={}));const Tt={},It=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Tt[t]=Tt[t]||new f);await Promise.all(i)},xt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=Tt[t]=Tt[t]||new f(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let Ot,Rt=0;const At=()=>Rt++,Dt={};let Lt;const Mt=t=>{Lt=t,Ot&&Ot.postMessage({type:"setBLog",body:{value:!!t}})};let Ft=!1;const Pt=t=>{Ft=t,Ot&&Ot.postMessage({type:"setBDebug",body:{value:!!t}})},kt={},Nt={},Bt={dip:{wasm:!0}},jt={std:{version:"2.0.0",path:C(E+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.2.20-dev-20251029130528",path:E,isInternal:!0}};let Ut=5;"undefined"!=typeof navigator&&(Ut=navigator.hardwareConcurrency?navigator.hardwareConcurrency-1:5),Dt[-3]=async t=>{Vt.onWasmLoadProgressChanged&&Vt.onWasmLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class Vt{static get engineResourcePaths(){return jt}static set engineResourcePaths(t){Object.assign(jt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return Lt}static set _onLog(t){Mt(t)}static get _bDebug(){return Ft}static set _bDebug(t){Pt(t)}static get _workerName(){return`${Vt._bundleEnv.toLowerCase()}.bundle.worker.js`}static get wasmLoadOptions(){return Vt._wasmLoadOptions}static set wasmLoadOptions(t){Object.assign(Vt._wasmLoadOptions,t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Tt[t]&&Tt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=Tt.core;e=!i||i.isEmpty,e||await It("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),St.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||St.MN_DYNAMSOFT_CORE==t)return;let e=Bt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=Tt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await xt(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await It(o);const i=B(jt),r={};for(let e of t)r[e]=Bt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:Vt._bundleEnv,wasmLoadOptions:Vt.wasmLoadOptions};let a=new f;if(e){s.needLoadCore=!0;let t=i[`${Vt._bundleEnv.toLowerCase()}Bundle`]+Vt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),Ot=new Worker(t),Ot.onerror=t=>{let e=new Error(t.message);a.reject(e)},Ot.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":Lt&&Lt(e.message);break;case"warning":console.warn(e.message);break;case"task":try{Dt[n](r),delete Dt[n]}catch(t){throw delete Dt[n],t}break;case"event":try{Dt[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!Lt,s.bd=Ft,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await It("core");let h=Rt++;Dt[h]=t=>{if(t.success)Object.assign(kt,t.versions),"{}"!==JSON.stringify(t.versions)&&(Vt._versions=t.versions),Vt.loadedWasmType=t.loadedWasmType,a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},Ot.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:st,worker:ot,getUserMedia:at,camera:await ht(),browser:nt.browser,version:nt.version,OS:nt.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=At();Dt[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)}},Ot.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.2.20-dev-20251029130528(Worker: ${kt.core&&kt.core.worker||"Not Loaded"}, Wasm: ${kt.core&&kt.core.wasm||"Not Loaded"})`}static enableLogging(){rt._onLog=console.log,Vt._onLog=console.log}static disableLogging(){rt._onLog=null,Vt._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Ot.postMessage({type:"cfd",id:n,body:{count:t}})})}}Vt._bSupportDce4Module=-1,Vt._bSupportIRTModule=-1,Vt._versions=null,Vt._bundleEnv="DCV",Vt._wasmLoadOptions={wasmType:"auto",pthreadPoolSize:Ut},Vt.loadedWasmType="ml-simd-pthread",Vt.browserInfo=nt;var Gt=Object.freeze({__proto__:null,CoreModule:Vt,get EnumBufferOverflowProtectionMode(){return p},get EnumCapturedResultItemType(){return lt},get EnumColourChannelUsageType(){return _},get EnumCornerType(){return ct},get EnumCrossVerificationStatus(){return _t},get EnumErrorCode(){return ut},get EnumGrayscaleEnhancementMode(){return dt},get EnumGrayscaleTransformationMode(){return ft},get EnumImageCaptureDistanceMode(){return Ct},get EnumImageFileFormat(){return Et},get EnumImagePixelFormat(){return v},get EnumImageTagType(){return gt},EnumIntermediateResultUnitType:vt,get EnumModuleName(){return St},get EnumPDFReadingMode(){return mt},get EnumRasterDataSource(){return pt},get EnumRegionObjectElementType(){return yt},get EnumSectionType(){return wt},get EnumTransformMatrixType(){return bt},ImageSourceAdapter:rt,_getNorImageData:W,_saveToFile:j,_toBlob:G,_toCanvas:U,_toImage:V,get bDebug(){return Ft},checkIsLink:t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),compareVersion:N,doOrWaitAsyncDependency:xt,getNextTaskID:At,handleEngineResourcePaths:B,innerVersions:kt,isArc:t=>!(!I(t)||!T(t.x)||!T(t.y)||!T(t.radius)||t.radius<0||!T(t.startAngle)||!T(t.endAngle)),isContour:t=>!!I(t)&&!!b(t.points)&&0!=t.points.length&&!t.points.some(t=>!L(t)),isDSImageData:O,isDSRect:R,isImageTag:A,isLineSegment:D,isObject:I,isOriginalDsImageData:t=>!(!x(t)||!T(t.bytes.length)&&!T(t.bytes.ptr)),isPoint:L,isPolygon:M,isQuad:F,isRect:P,isSimdSupported:async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),mapAsyncDependency:Tt,mapPackageRegister:Nt,mapTaskCallBack:Dt,get onLog(){return Lt},productNameMap:Y,requestResource:k,setBDebug:Pt,setOnLog:Mt,waitAsyncDependency:It,get worker(){return Ot},workerAutoResources:Bt}),Wt={license:"",scanMode:t.EnumScanMode.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:Vt.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:o,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Yt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ht=(async()=>{})().constructor;class Xt extends Ht{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,Yt(t)?e=t:"function"==typeof t&&(e=new Ht(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Yt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function zt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function qt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Kt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Zt=(async()=>{})().constructor;let Jt=class extends Zt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Kt(t)?e=t:"function"==typeof t&&(e=new Zt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Kt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},$t=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=At();Dt[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)}},Ot.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Ot.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=At();Dt[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)}},Ot.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var Qt={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1};const te=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};let ee=class{constructor(t){this._irrRegistryState=Qt,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),te(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach((t,e)=>{i[e]=t}),t._observedTaskMap.clear()}return await new Promise((t,n)=>{let r=At();Dt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Ot.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),te(this),await new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Ot.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const ie="undefined"==typeof self,ne="function"==typeof importScripts,re=(()=>{if(!ne){if(!ie&&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"./"}})(),se=t=>{if(null==t&&(t="./"),ie||ne);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var oe;Vt.engineResourcePaths.cvr={version:"3.2.20-dev-20251030140710",path:re,isInternal:!0},Bt.cvr={js:!0,wasm:!0,deps:[St.MN_DYNAMSOFT_LICENSE,St.MN_DYNAMSOFT_IMAGE_PROCESSING,St.MN_DYNAMSOFT_NEURAL_NETWORK]},Bt.dnn={wasm:!0,deps:[St.MN_DYNAMSOFT_IMAGE_PROCESSING]},Nt.cvr={};const ae="2.0.0";"string"!=typeof Vt.engineResourcePaths.std&&N(Vt.engineResourcePaths.std.version,ae)<0&&(Vt.engineResourcePaths.std={version:ae,path:se(re+`../../dynamsoft-capture-vision-std@${ae}/dist/`),isInternal:!0});const he="3.0.10";(!Vt.engineResourcePaths.dip||"string"!=typeof Vt.engineResourcePaths.dip&&N(Vt.engineResourcePaths.dip.version,he)<0)&&(Vt.engineResourcePaths.dip={version:he,path:se(re+`../../dynamsoft-image-processing@${he}/dist/`),isInternal:!0});const le="2.0.10";(!Vt.engineResourcePaths.dnn||"string"!=typeof Vt.engineResourcePaths.dnn&&N(Vt.engineResourcePaths.dnn.version,le)<0)&&(Vt.engineResourcePaths.dnn={version:le,path:se(re+`../../dynamsoft-capture-vision-dnn@${le}/dist/`),isInternal:!0});let ce=class{static getVersion(){return this._version}};var ue,de,fe,ge,me,pe,_e,ve,ye,we,Ee,Ce,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le,Me,Fe;function Pe(t,e){if(t){if(t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}if(t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}Pe(t.referencedItem,e)}}function ke(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function Ne(t){return{type:lt.CRIT_ORIGINAL_IMAGE,referenceItem:null,targetROIDefName:"",taskName:"",imageData:t,toCanvas:()=>U(t),toImage:e=>V(e,t),toBlob:e=>G(e,t)}}function Be(t){let e=!1;const i=[ut.EC_UNSUPPORTED_JSON_KEY_WARNING,ut.EC_LICENSE_AUTH_QUOTA_EXCEEDED,ut.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}ce._version=`3.2.20-dev-20251030140710(Worker: ${null===(oe=kt.cvr)||void 0===oe?void 0:oe.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ue||(ue={}));const je={onTaskResultsReceived:()=>{},isFilter:!0};Dt[-2]=async t=>{Ue.onDataLoadProgressChanged&&Ue.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let Ue=class t{constructor(){de.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(Vt.browserInfo.OS)?2048:4096,this.onCaptureError=null,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._dynamsoft=!0,fe.set(this,null),ge.set(this,null),me.set(this,null),pe.set(this,null),_e.set(this,null),ve.set(this,new Set),ye.set(this,new Set),we.set(this,new Set),Ee.set(this,500),Ce.set(this,0),Se.set(this,0),be.set(this,!1),Te.set(this,!1),Ie.set(this,!1),xe.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return zt(this,Ie,"f")}static async createInstance(e=!0){if(!Nt.license)throw Error("The `license` module cannot be found.");await Nt.license.dynamsoft(),await Vt.loadWasm();const i=new t,n=new Jt;let r=At();return Dt[r]=async e=>{e.success?(i._instanceID=e.instanceID,i._currentSettings=JSON.parse(JSON.parse(e.outputSettings).data),t._isNoOnnx=e.isNoOnnx,ce._version=`3.2.20-dev-20251030140710(Worker: ${kt.cvr.worker}, Wasm: ${e.version})`,qt(i,Te,!0,"f"),qt(i,pe,i.getIntermediateResultManager(),"f"),qt(i,Te,!1,"f"),n.resolve(i)):Be({message:e.message,rj:n.reject,stack:e.stack,functionName:"createInstance"})},Ot.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendDLModelBuffer(e,i){return await Vt.loadWasm(),t._isNoOnnx?Promise.reject("Model not supported in the current environment."):await new Promise((t,n)=>{let r=At();const s=B(Vt.engineResourcePaths);let o;Dt[r]=async e=>{if(e.success){const i=JSON.parse(e.response);return 0!==i.errorCode&&Be({message:i.errorString?i.errorString:"Append Model Buffer Failed.",rj:n,errorCode:i.errorCode,functionName:"appendDLModelBuffer"}),t(i)}Be({message:e.message,rj:n,stack:e.stack,functionName:"appendDLModelBuffer"})},i?o=i:"DCV"===Vt._bundleEnv?o=s.dcvData+"models/":"DBR"===Vt._bundleEnv&&(o=s.dbrBundle+"models/"),Ot.postMessage({type:"cvr_appendDLModelBuffer",id:r,body:{modelName:e,path:o}})})}static async clearDLModelBuffers(){return await new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success)return t();Be({message:i.message,rj:e,stack:i.stack,functionName:"clearDLModelBuffers"})},Ot.postMessage({type:"cvr_clearDLModelBuffers",id:i})})}async _singleFrameModeCallback(t){for(let e of zt(this,ve,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived(Ne(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,zt(this,fe,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}),zt(this,de,"m",Ae).call(this,i)}setInput(t){if(ke(this),!t)return zt(this,xe,"f")&&(zt(this,pe,"f").removeResultReceiver(zt(this,xe,"f")),qt(this,xe,null,"f")),void qt(this,fe,null,"f");qt(this,fe,t,"f"),t.isCameraEnhancer&&zt(this,pe,"f")&&(zt(this,fe,"f")._intermediateResultReceiver.isDce=!0,zt(this,pe,"f").addResultReceiver(zt(this,fe,"f")._intermediateResultReceiver),qt(this,xe,zt(this,fe,"f")._intermediateResultReceiver,"f"))}getInput(){return zt(this,fe,"f")}addImageSourceStateListener(t){if(ke(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&zt(this,ye,"f").add(t)}removeImageSourceStateListener(t){return ke(this),zt(this,ye,"f").delete(t)}addResultReceiver(t){if(ke(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(zt(this,ve,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){ke(this),zt(this,ve,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of zt(this,ve,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Jt;let i=At();return Dt[i]=async t=>{t.success?e.resolve():Be({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},Ot.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(ke(this),!t._dynamsoft)throw new Error("User defined CapturedResultFilter is not supported.");if(!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");zt(this,we,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){ke(this),zt(this,we,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(zt(this,pe,"f").removeResultReceiver(je),0===zt(this,we,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!1,[lt.CRIT_DETECTED_QUAD]:!1,[lt.CRIT_DESKEWED_IMAGE]:!1,[lt.CRIT_ENHANCED_IMAGE]:!1},e={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!1,[lt.CRIT_DETECTED_QUAD]:!1,[lt.CRIT_DESKEWED_IMAGE]:!1,[lt.CRIT_ENHANCED_IMAGE]:!1};return await zt(this,de,"m",De).call(this,t),void await zt(this,de,"m",Le).call(this,e)}for(let t of zt(this,we,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(lt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(lt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(lt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(lt.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(lt.CRIT_BARCODE)&&([...zt(this,pe,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||zt(this,pe,"f").addResultReceiver(je)),await zt(this,de,"m",De).call(this,t.verificationEnabled),await zt(this,de,"m",Le).call(this,t.duplicateFilterEnabled),await zt(this,de,"m",Me).call(this,t.duplicateForgetTime)}async startCapturing(e){if(ke(this),!this._isPauseScan)return;if(!zt(this,fe,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);for(let t of zt(this,we,"f"))await this.addResultFilter(t);const i=B(Vt.engineResourcePaths);return void 0!==zt(this,fe,"f").singleFrameMode&&"disabled"!==zt(this,fe,"f").singleFrameMode?(this._templateName=e,void zt(this,fe,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):zt(this,me,"f")&&zt(this,me,"f").isPending?zt(this,me,"f"):(qt(this,me,new Jt((t,n)=>{if(this.disposed)return;let r=At();Dt[r]=async i=>{zt(this,me,"f")&&!zt(this,me,"f").isFulfilled&&(i.success?(this._isPauseScan=!1,this._isOutputOriginalImage=i.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&zt(this,fe,"f").startFetching(),this._loopReadVideo(e),t()},0)):Be({message:i.message,rj:n,stack:i.stack,functionName:"startCapturing"}))},Ot.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:i}})}),"f"),await zt(this,me,"f"))}stopCapturing(){ke(this),zt(this,fe,"f")&&(zt(this,fe,"f").isCameraEnhancer&&void 0!==zt(this,fe,"f").singleFrameMode&&"disabled"!==zt(this,fe,"f").singleFrameMode?zt(this,fe,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(zt(this,de,"m",Fe).call(this),zt(this,fe,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,qt(this,me,null,"f"),zt(this,fe,"f").setColourChannelUsageType(_.CCUT_AUTO)))}async containsTask(t){return ke(this),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));Be({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},Ot.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async switchCapturingTemplate(t){this.stopCapturing(),await this.startCapturing(t)}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(qt(this,be,!0,"f"),zt(this,fe,"f").isBufferEmpty())if(zt(this,fe,"f").hasNextImageToFetch())for(let t of zt(this,ye,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_BUFFER_EMPTY);else if(!zt(this,fe,"f").hasNextImageToFetch())for(let t of zt(this,ye,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ue.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||zt(this,fe,"f").isBufferEmpty()&&zt(this,fe,"f").isCameraEnhancer)try{zt(this,fe,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=zt(this,fe,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),zt(this,fe,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(zt(this,fe,"f").isCameraEnhancer&&zt(this,fe,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=zt(this,fe,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of zt(this,ve,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived(Ne(this._dsImage));const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null,zt(this,fe,"f").isCameraEnhancer&&zt(this,fe,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify});for(let t of zt(this,we,"f")){const e=t;e.onOriginalImageResultReceived(n),e.onDecodedBarcodesReceived(n),e.onRecognizedTextLinesReceived(n),e.onProcessedDocumentResultReceived(n),e.onParsedResultsReceived(n)}zt(this,de,"m",Ae).call(this,n);const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{zt(this,fe,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{zt(this,fe,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async getClarity(t,e,i,n,r){const{bytes:s,width:o,height:a,stride:h,format:l}=t;let c=At();return new Promise((t,u)=>{Dt[c]=async e=>{e.success?t(e.clarity):Be({message:e.message,rj:u,stack:e.stack,functionName:"getClarity"})},Ot.postMessage({type:"cvr_getClarity",id:c,instanceID:this._instanceID,body:{bytes:s,width:o,height:a,stride:h,format:l,bitcount:e,wr:i,hr:n,grayThreshold:r}},[s.buffer])})}async capture(e,i){let n;if(ke(this),i||(i=t._defaultTemplate),qt(this,be,!1,"f"),O(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await k(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(qt(this,Se,this.maxImageSideLength/o,"f"),i=Math.round(r*zt(this,Se,"f")),n=Math.round(s*zt(this,Se,"f"))):(i=r,n=s),zt(this,ge,"f")||qt(this,ge,document.createElement("canvas"),"f");const a=zt(this,ge,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(qt(this,Se,this.maxImageSideLength/o,"f"),i=Math.round(r*zt(this,Se,"f")),n=Math.round(s*zt(this,Se,"f"))):(i=r,n=s),zt(this,ge,"f")||qt(this,ge,document.createElement("canvas"),"f");const a=zt(this,ge,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=At();const l=new Jt;return Dt[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;e.bytes=i.bytes,zt(this,de,"m",Oe).call(this,t,e),i.isScanner||qt(this,Se,0,"f"),zt(this,de,"m",Re).call(this,t,e);const n=Date.now();return n-zt(this,Ce,"f")>zt(this,Ee,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),qt(this,Ce,n,"f")),l.resolve(t)}catch(i){Be({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else Be({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),Ot.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:zt(this,be,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(ke(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await k(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=At();Dt[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&Be({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}Be({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},Ot.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return ke(this),await new Promise((i,n)=>{let r=At();Dt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Be({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}Be({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},Ot.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,null,2,function(t,e){return e instanceof Array?JSON.stringify(e):e},2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return ke(this),await new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Be({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}Be({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},Ot.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return ke(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&Be({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}Be({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},Ot.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return ke(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=At();Dt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&Be({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}Be({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},Ot.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return ke(this),await new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Be({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}Be({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},Ot.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return zt(this,_e,"f")||qt(this,_e,new $t(this),"f"),zt(this,_e,"f")}getIntermediateResultManager(){if(ke(this),!zt(this,Te,"f")&&0!==Vt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return zt(this,pe,"f")||qt(this,pe,new ee(this),"f"),zt(this,pe,"f")}static async setGlobalIntraOpNumThreads(t=0){return t>4||t<0?Promise.reject(new RangeError("'intraOpNumThreads' should be between 0 and 4.")):(await Vt.loadWasm(),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e();Be({message:t.message,rj:i,stack:t.stack,functionName:"setGlobalIntraOpNumThreads"})},Ot.postMessage({type:"cvr_setGlobalIntraOpNumThreads",id:n,body:{intraOpNumThreads:t}})}))}async parseRequiredResources(t){return ke(this),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));Be({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},Ot.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){ke(this),zt(this,me,"f")&&this.stopCapturing(),qt(this,fe,null,"f"),zt(this,ve,"f").clear(),zt(this,ye,"f").clear(),zt(this,we,"f").clear(),zt(this,pe,"f")._intermediateResultReceiverSet.clear(),qt(this,Ie,!0,"f");let t=At();Dt[t]=t=>{t.success||Be({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},Ot.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:zt(this,fe,"f"),promiseStartScan:zt(this,me,"f"),intermediateResultManager:zt(this,pe,"f"),bufferdItemsManager:zt(this,_e,"f"),resultReceiverSet:zt(this,ve,"f"),isaStateListenerSet:zt(this,ye,"f"),resultFilterSet:zt(this,we,"f"),compressRate:zt(this,Se,"f"),canvas:zt(this,ge,"f"),isScanner:zt(this,be,"f"),innerUseTag:zt(this,Te,"f"),isDestroyed:zt(this,Ie,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}Be({message:i.message,rj:e,stack:i.stack,functionName:""})},Ot.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};fe=new WeakMap,ge=new WeakMap,me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,xe=new WeakMap,de=new WeakSet,Oe=function(t,e){var i,n,r,s,o,a,h,l,c,u,d,f;for(let g=0;g{let n=At();Dt[n]=async t=>{if(t.success)return e(t.result);Be({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Ot.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Le=async function(t){return ke(this),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e(t.result);Be({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Ot.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},Me=async function(t){return ke(this),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return e(t.result);Be({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Ot.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},Fe=async function(){let t=At();const e=new Jt;return Dt[t]=async t=>{if(t.success)return e.resolve();Be({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},Ot.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},Ue._defaultTemplate="Default",Ue._isNoOnnx=!1;let Ve=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}};var Ge;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadSingleBarcode",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Ge||(Ge={}));var We=Object.freeze({__proto__:null,CaptureVisionRouter:Ue,CaptureVisionRouterModule:ce,CapturedResultReceiver:Ve,get EnumImageSourceState(){return ue},get EnumPresetTemplate(){return Ge},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=vt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Ye="undefined"==typeof self,He="function"==typeof importScripts,Xe=(()=>{if(!He){if(!Ye&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();Vt.engineResourcePaths.dce={version:"4.3.3-dev-20251029130621",path:Xe,isInternal:!0},Bt.dce={wasm:!1,js:!1},Nt.dce={};let ze,qe,Ke,Ze,Je;function $e(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Qe(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(ze=navigator,qe=ze.userAgent,Ke=ze.platform,Ze=ze.mediaDevices),function(){if(!Ye){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:ze.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:Ke,search:"Win"},Mac:{str:Ke},Linux:{str:Ke}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||qe,o=r.search||e,a=r.verStr||qe,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||qe,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=qe.indexOf("Windows NT")&&(r="HarmonyOS"),Je={browser:i,version:n,OS:r}}Ye&&(Je={browser:"ssr",version:0,OS:"ssr"})}();const ti="undefined"!=typeof WebAssembly&&qe&&!(/Safari/.test(qe)&&!/Chrome/.test(qe)&&/\(.+\s11_2_([2-6]).*\)/.test(qe)),ei=!("undefined"==typeof Worker),ii=!(!Ze||!Ze.getUserMedia),ni=async()=>{let t=!1;if(ii)try{(await Ze.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===Je.browser&&Je.version>66||"Safari"===Je.browser&&Je.version>13||"OPR"===Je.browser&&Je.version>43||"Edge"===Je.browser&&Je.version;var ri={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,E,C,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some(function(e){return"function"==typeof e.contains&&e.contains(t,!0)})},complexity:function(){return this._objects.reduce(function(t,e){return t+(e.complexity?e.complexity():0)},0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach(function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))}),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var S=Math.sqrt(1-E/(_*v));i*=S,s*=S}else C=(o===a?-1:1)*Math.sqrt(E/(_*y+v*w));var T=C*i*p/s,I=-C*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kC)for(var T=1,I=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var I,x,O,R=C.length,A=R;R--;)I=(O=1-(f=C[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(function(t){for(var i=t.slice(0),n={},r=1;r=e})}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach(function(t){t.cancel()}),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter(function(e){return"object"==typeof e.target&&e.target.canvas===t});return e.forEach(function(t){t.cancel()}),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach(function(t){t.cancel()}),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find(function(e){return e.cancel===t})},findAnimationsByTarget:function(t){return t?this.filter(function(e){return e.target===t}):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map(function(t,e){return v[e]-_[e]}):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map(function(t,e){return m(n,_[e],y[e],c)}):m(n,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=r,!o){if(!f(w,E,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,E,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",S=0,b=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),E.minX=i,E.minY=n,E.viewBoxWidth=r,E.viewBoxHeight=o,y?(E.width=r,E.height=o):(E.width=s(d),E.height=s(f),c=E.width/r,u=E.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=E.width-r*c,b=E.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),E}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function E(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function C(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),C(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),C(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),C=_(f,y,w),S=e.gestureScale;if(C)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=E(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y(function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),C(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=E(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),C(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=E,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach(function(e){i[e]=t[e]}),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach(function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s})}(0,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,function(t,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(e){this[e]!==i[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)},this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find(function(e){return!0===t[e]}):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),r.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e:e,selected:r}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach(function(i){e[i]=t[i]}),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach(function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})}),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e:e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter(function(e){return!e.onSelect({e:t})})),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){r.clear(),r._setBgOverlay(n,function(){s?r._enlivenObjects([s],function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)}):r.__setupCanvas.call(r,n,t,o,e)})},i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach(function(t,e){r.insertAt(t,e)}),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],function(e){r[t]=e[0],i[t]=!0,n&&n()}):this["set"+b.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},null,i):e&&e([])},_toDataURL:function(t,e){this.clone(function(i){e(i.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,i){this.clone(function(n){i(n.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(i,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,function(){i.renderAll(),t&&t(i)}),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=l>y||c>w;v=E||(l<.9*y||c<.9*w)&&y>h&&w>h,E&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach(function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])}),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var o=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,function(){var t=s?new o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof n?n=E[n]:n-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof r?r=C[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,o=b.util.sin(n)*r;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach(function(t){r[t]=e[t]}),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl(function(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,function(t){delete t.points,i&&i(t)},"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r}),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter(function(t){return t&&!t.isNeutralState()}),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,function(){var n=new b.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,function(t,n){e&&e(new b.Image(t,i),n)},null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach(function(t){t.applyTo(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=n,C[s+3]=S?m[s+3]:r}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(b-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+C*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+C*n+o,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&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 n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},si={};function oi(t){var e=si[t];if(void 0!==e)return e.exports;var i=si[t]={exports:{}};return ri[t](i,i.exports,oi),i.exports}oi.d=(t,e)=>{for(var i in e)oi.o(e,i)&&!oi.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},oi.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ai={};(()=>{let t;oi.d(ai,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?oi(653).fabric:{version:"5.2.1"}})();var hi,li,ci,ui,di=ai.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"}(hi||(hi={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(li||(li={})),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"}(ci||(ci={})),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"}(ui||(ui={}));const fi=t=>"number"==typeof t&&!Number.isNaN(t),gi=t=>"string"==typeof t;var mi,pi,_i,vi,yi,wi,Ei,Ci,Si,bi,Ti;!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"}(yi||(yi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(wi||(wi={}));let Ii=class{get mediaType(){return new Map([["rect",hi.DIMT_RECTANGLE],["quad",hi.DIMT_QUADRILATERAL],["text",hi.DIMT_TEXT],["arc",hi.DIMT_ARC],["image",hi.DIMT_IMAGE],["polygon",hi.DIMT_POLYGON],["line",hi.DIMT_LINE],["group",hi.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch($e(this,pi,"f")){case li.DIS_DEFAULT:return"default";case li.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"===$e(this,_i,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===$e(this,_i,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Qe(this,_i,t,"f")}get coordinateBase(){return $e(this,_i,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(mi.add(this),pi.set(this,void 0),_i.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&&!fi(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(li.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(li.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(li.DIS_SELECTED):this.setState(li.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){Qe(this,pi,t,"f")}getState(){return $e(this,pi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Ai),actionName:"modifyPolygon",pointIndex:i}),t},{}),Qe(this,Ci,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map(t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2})),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce(function(t,e,n){return t["p"+n]=new di.Control({positionHandler:Oi,actionHandler:Di(n>0?n-1:i,Ai),actionName:"modifyPolygon",pointIndex:n}),t},{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=di.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){$e(this,Ci,"f")&&this.setPolygon($e(this,Ci,"f"))}setPolygon(t){if(!M(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Qe(this,Ci,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 $e(this,Ci,"f")?JSON.parse(JSON.stringify($e(this,Ci,"f"))):null}};Ci=new WeakMap;Si=new WeakMap,bi=new WeakMap;const Mi=t=>{let e=(t=>t.split("\n").map(t=>t.split("\t")))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Qe(this,ki,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 $e(this,ki,"f")?JSON.parse(JSON.stringify($e(this,ki,"f"))):null}}ki=new WeakMap;let Bi=class extends Ii{constructor(t){super(new di.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(li.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(li.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("deselected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map(t=>t.getDrawingItem())}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}};const ji=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Ui=t=>!!gi(t)&&""!==t,Vi=t=>!(!ji(t)||"id"in t&&!fi(t.id)||"lineWidth"in t&&!fi(t.lineWidth)||"fillStyle"in t&&!Ui(t.fillStyle)||"strokeStyle"in t&&!Ui(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Ui(t.fontFamily)||"fontSize"in t&&!fi(t.fontSize));class Gi{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(P(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!R(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Wi,Yi;class Hi{constructor(){Wi.set(this,new Map),Yi.set(this,!1)}get disposed(){return $e(this,Yi,"f")}on(t,e){t=t.toLowerCase();const i=$e(this,Wi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else $e(this,Wi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=$e(this,Wi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=$e(this,Wi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=$e(this,Wi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){Qe(this,Yi,!0,"f")}}function Xi(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 zi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function qi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Wi=new WeakMap,Yi=new WeakMap;const Ki=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};class Zi{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*r[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Zi.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return Zi.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Zi.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Ji,$i,Qi,tn,en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,En,Cn,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Er,Cr,Sr,br,Tr;class Ir{static createDrawingStyle(t){if(!Vi(t))throw new Error("Invalid style definition.");let e,i=Ir.USER_START_STYLE_ID;for(;$e(Ir,Ji,"f",$i).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in $e(Ir,Ji,"f",Qi))n.hasOwnProperty(t)||(n[t]=$e(Ir,Ji,"f",Qi)[t]);return $e(Ir,Ji,"f",$i).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=$e(Ir,Ji,"f",$i).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($e(Ir,Ji,"f",$i).values())))}static _updateDrawingStyle(t,e){if(!Vi(e))throw new Error("Invalid style definition.");const i=$e(Ir,Ji,"f",$i).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Ji=Ir,Ir.STYLE_BLUE_STROKE=1,Ir.STYLE_GREEN_STROKE=2,Ir.STYLE_ORANGE_STROKE=3,Ir.STYLE_YELLOW_STROKE=4,Ir.STYLE_BLUE_STROKE_FILL=5,Ir.STYLE_GREEN_STROKE_FILL=6,Ir.STYLE_ORANGE_STROKE_FILL=7,Ir.STYLE_YELLOW_STROKE_FILL=8,Ir.STYLE_BLUE_STROKE_TRANSPARENT=9,Ir.STYLE_GREEN_STROKE_TRANSPARENT=10,Ir.STYLE_ORANGE_STROKE_TRANSPARENT=11,Ir.USER_START_STYLE_ID=1024,$i={value:new Map([[Ir.STYLE_BLUE_STROKE,{id:Ir.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Ir.STYLE_GREEN_STROKE,{id:Ir.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}],[Ir.STYLE_ORANGE_STROKE,{id:Ir.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}],[Ir.STYLE_YELLOW_STROKE,{id:Ir.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Ir.STYLE_BLUE_STROKE_FILL,{id:Ir.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}],[Ir.STYLE_GREEN_STROKE_FILL,{id:Ir.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}],[Ir.STYLE_ORANGE_STROKE_FILL,{id:Ir.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}],[Ir.STYLE_YELLOW_STROKE_FILL,{id:Ir.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}],[Ir.STYLE_BLUE_STROKE_TRANSPARENT,{id:Ir.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ir.STYLE_GREEN_STROKE_TRANSPARENT,{id:Ir.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Ir.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Ir.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Qi={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&&(di.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(di.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),di.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},di.Object.prototype.transparentCorners=!1,di.Object.prototype.cornerSize=20,di.Object.prototype.touchCornerSize=100,di.Object.prototype.cornerColor="rgb(254,142,20)",di.Object.prototype.cornerStyle="circle",di.Object.prototype.strokeUniform=!0,di.Object.prototype.hasBorders=!1,di.Canvas.prototype.containerClass="",di.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=di.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},di.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;ii&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class xr{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 di.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])},0)}}),e.on("before:selection:cleared",function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.fabricCanvas.id=e,this.id=e,e){case xr.DDN_LAYER_ID:n=Ir.getDrawingStyle(Ir.STYLE_BLUE_STROKE),r=Ir.getDrawingStyle(Ir.STYLE_BLUE_STROKE_FILL);break;case xr.DBR_LAYER_ID:n=Ir.getDrawingStyle(Ir.STYLE_ORANGE_STROKE),r=Ir.getDrawingStyle(Ir.STYLE_ORANGE_STROKE_FILL);break;case xr.DLR_LAYER_ID:n=Ir.getDrawingStyle(Ir.STYLE_GREEN_STROKE),r=Ir.getDrawingStyle(Ir.STYLE_GREEN_STROKE_FILL);break;default:n=Ir.getDrawingStyle(Ir.STYLE_YELLOW_STROKE),r=Ir.getDrawingStyle(Ir.STYLE_YELLOW_STROKE_FILL)}for(let t of Ii.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Ir.getDrawingStyle(t.styleId);return Ir.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems(e=>e._mediaType===t);for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Ir.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Ir.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Ir.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Ir.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Ir.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Ii))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ii.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Ir.getDrawingStyle(t.styleId);else{s=Ir.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Ir.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Ir.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ii.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Ir.getDrawingStyle(t.styleId);else{s=Ir.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Ir.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Ir.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase()):e=Ii.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Ii.arrStyleSelectors;const n=Ir.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&hi.DIMT_RECTANGLE&&n.push("rect"),i&hi.DIMT_QUADRILATERAL&&n.push("quad"),i&hi.DIMT_TEXT&&n.push("text"),i&hi.DIMT_ARC&&n.push("arc"),i&hi.DIMT_IMAGE&&n.push("image"),i&hi.DIMT_POLYGON&&n.push("polygon"),i&hi.DIMT_LINE&&n.push("line");const r=[];e&li.DIS_DEFAULT&&r.push("default"),e&li.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}xr.DDN_LAYER_ID=1,xr.DBR_LAYER_ID=2,xr.DLR_LAYER_ID=3,xr.USER_DEFINED_LAYER_BASE_ID=100,xr.TIP_LAYER_ID=999;class Or{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new xr(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 Fi{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),tn.set(this,void 0),en.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Qe(this,en,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},$e(this,tn,"f")),"f")}getDuration(){return $e(this,tn,"f")}}tn=new WeakMap,en=new WeakMap;class Ar{constructor(){nn.add(this),rn.set(this,void 0),sn.set(this,void 0),on.set(this,void 0),an.set(this,!0),this._drawingLayerManager=new Or}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=xr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==xr.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()!==xr.TIP_LAYER_ID)}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ji(e=t)&&L(e.topLeftPoint)&&fi(e.width))||e.width<=0||!fi(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Qe(this,rn,JSON.parse(JSON.stringify(t)),"f"),$e(this,rn,"f").coordinateBase||($e(this,rn,"f").coordinateBase="view"),Qe(this,on,t.duration,"f"),$e(this,nn,"m",un).call(this)}getTipConfig(){return $e(this,rn,"f")?$e(this,rn,"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()),Qe(this,an,t,"f")}isTipVisible(){return $e(this,an,"f")}updateTipMessage(t){if(!$e(this,rn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Ir.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(xr.TIP_LAYER_ID)||this._createDrawingLayer(xr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=$e(this,nn,"m",hn).call(this,t,$e(this,rn,"f").topLeftPoint.x,$e(this,rn,"f").topLeftPoint.y,$e(this,rn,"f").width,$e(this,rn,"f").coordinateBase,this._tipStyleId),$e(this,nn,"m",ln).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",$e(this,an,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),$e(this,sn,"f")&&clearTimeout($e(this,sn,"f")),$e(this,on,"f")>=0&&Qe(this,sn,setTimeout(()=>{$e(this,nn,"m",cn).call(this)},$e(this,on,"f")),"f")}}rn=new WeakMap,sn=new WeakMap,on=new WeakMap,an=new WeakMap,nn=new WeakSet,hn=function(t,e,i,n,r,s){const o=new Rr(t,e,i,n,s);return o.coordinateBase=r,o},ln=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},cn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},un=function(){if(!this._tip)return;const t=$e(this,rn,"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(),dn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Qe(this,dn,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return $e(this,dn,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach(t=>t.remove())}}dn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Dr);class Lr extends Ar{static get engineResourcePath(){const t=B(Vt.engineResourcePaths);return"DCV"===Vt._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Lr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Lr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Lr.engineResourcePath)}static async createInstance(t){const e=new Lr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Lr.engineResourcePath)),await e.setUIElement(t||Lr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==$e(this,Cn,"f")){if(Qe(this,Cn,t,"f"),$e(this,fn,"m",Tn).call(this))Qe(this,_n,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"),!$e(this,_n,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Qe(this,_n,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}$e(this,fn,"m",Tn).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 $e(this,Cn,"f")}get disposed(){return $e(this,bn,"f")}constructor(){super(),fn.add(this),gn.set(this,void 0),mn.set(this,void 0),pn.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",_n.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._poweredBy=null,vn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,yn.set(this,!1),wn.set(this,!1),En.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{$e(this,fn,"m",An).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout(()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&$e(this,fn,"m",Rn).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Lr._onLog&&Lr._onLog("window resize event triggered."),$e(this,En,"f").width===document.documentElement.clientWidth&&$e(this,En,"f").height===document.documentElement.clientHeight||($e(this,En,"f").width=document.documentElement.clientWidth,$e(this,En,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Cn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!$e(this,fn,"m",Tn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout(()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)},0)}),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Sn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{(e=JSON.parse(JSON.stringify(e))).forEach(t=>Lr._transformCoordinates(t,i,n,r,s,o,a));const c=new Ni({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},l);for(let t of h)c.addNote(t);t.addDrawingItems([c]),$e(this,Sn,"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(xr.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,Ir.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(xr.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,Ir.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(xr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===_t.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Ir.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case lt.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(xr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===_t.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Ir.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case lt.CRIT_PARSED_RESULT:case lt.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}}},bn.set(this,!1),this.eventHandler=new Hi,this.eventHandler.on("content:updated",()=>{$e(this,gn,"f")&&clearTimeout($e(this,gn,"f")),Qe(this,gn,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",()=>{$e(this,mn,"f")&&clearTimeout($e(this,mn,"f")),Qe(this,mn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ki(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),$e(this,fn,"m",Tn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Je.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Qe(this,_n,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||$e(this,fn,"m",Tn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||$e(this,fn,"m",Tn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||$e(this,fn,"m",An).call(this),$e(this,fn,"m",Tn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),$e(this,fn,"m",Tn).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;Lr._onLog&&Lr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()}));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}$e(this,En,"f").width=document.documentElement.clientWidth,$e(this,En,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;$e(this,fn,"m",Tn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),$e(this,fn,"m",An).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Qe(this,_n,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return $e(this,_n,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!$e(this,_n,"f"))return;if($e(this,_n,"f").style.objectFit=t,$e(this,fn,"m",Tn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();$e(this,fn,"m",Dn).call(this,e,i),$e(this,fn,"m",In).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if($e(this,fn,"m",Tn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=$e(this,_n,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=$e(this,_n,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){R(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):P(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=Gi.convert(this.scanRegion,t.width,t.height,this);Qe(this,vn,e,"f"),$e(this,pn,"f")&&clearTimeout($e(this,pn,"f")),Qe(this,pn,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}$e(this,fn,"m",In).call(this,t,e),$e(this,fn,"m",Dn).call(this,t,e)},0),"f")}getConvertedRegion(){return $e(this,vn,"f")}setScanRegion(t){if(null!=t&&!R(t)&&!P(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=$e(this,_n,"f").videoWidth,i=$e(this,_n,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=$e(this,_n,"f").videoWidth,e=$e(this,_n,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove()),$e(this,Sn,"f").length=0}dispose(){this._unbindUI(),Qe(this,bn,!0,"f")}}gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,En=new WeakMap,Cn=new WeakMap,Sn=new WeakMap,bn=new WeakMap,fn=new WeakSet,Tn=function(){return"disabled"!==this._singleFrameMode},In=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},xn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},On=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Rn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},An=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Dn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach(e=>t.attachShader(i,e)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);Qe(this,Fn,{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"),Qe(this,Pn,e(t),"f"),Qe(this,Mn,i(t),"f"),Qe(this,Ln,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,o,m)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[ui.GREY,ui.GREY32].includes(p)?1:0);let _,v,y=Zi.translate(Zi.identity(),-1,-1);y=Zi.scale(y,2,2),y=Zi.scale(y,1/t.canvas.width,1/t.canvas.height),_=Zi.translate(y,u,d),_=Zi.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=Zi.translate(Zi.identity(),1,0),v=Zi.scale(v,-1,1),v=Zi.translate(v,a/i,h/n),v=Zi.scale(v,l/i,c/n)):(v=Zi.translate(Zi.identity(),a/i,h/n),v=Zi.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,$e(this,Mn,"f"),e),y(t,$e(this,Fn,"f"),$e(this,Pn,"f"),$e(this,Mn,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){Mr._onLog&&Mr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Mr._onLog&&Mr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===ui.GREY?ui.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Mr._onLog&&Mr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(Mr._onLog&&(r=Date.now(),Mr._onLog("transformPixelFormat(), START: "+r)),e===i)return Mr._onLog&&Mr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[ui.RGBA,ui.RBGA,ui.GRBA,ui.GBRA,ui.BRGA,ui.BGRA];if(o.includes(e))if(i===ui.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=Mr._onLog)||void 0===n||n.call(Mr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||ui.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(ui.GREY===y&&w.length{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Pr{static get version(){return"4.3.3-dev-20251029130621"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find(t=>e.includes(t.label.toLowerCase()));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!r.length)return null;const s=r.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(s)return s.deviceId;const o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Je.OS))return Pr.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(Je.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise(async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise(t=>{g=t}),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise(t=>{setTimeout(t,1e3)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}})}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!$e(this,Jn,"f"))return"closed";if("pending"===$e(this,Jn,"f"))return"opening";if("fulfilled"===$e(this,Jn,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Pr.isStorageAvailable("localStorage")?Qe(this,zn,!0,"f"):(Qe(this,zn,!1,"f"),console.warn("Local storage is unavailable")):Qe(this,zn,!1,"f")}get ifSaveLastUsedCamera(){return $e(this,zn,"f")}get isVideoPlaying(){return!(!$e(this,Un,"f")||$e(this,Un,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=$e(this,nr,"f"))||void 0===e||e.removeEventListener("click",$e(this,ir,"f")),null===(i=$e(this,nr,"f"))||void 0===i||i.removeEventListener("touchend",$e(this,ir,"f")),null===(n=$e(this,nr,"f"))||void 0===n||n.removeEventListener("touchmove",$e(this,er,"f")),Qe(this,nr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Je.OS)?(t.addEventListener("touchend",$e(this,ir,"f")),t.addEventListener("touchmove",$e(this,er,"f"))):t.addEventListener("click",$e(this,ir,"f")))}get tapFocusEventBoundEl(){return $e(this,nr,"f")}get disposed(){return $e(this,dr,"f")}constructor(t){var e,i;jn.add(this),Un.set(this,null),Vn.set(this,void 0),this._zoomPreSetting=null,Gn.set(this,()=>{"opened"===this.state&&$e(this,ar,"f").fire("resumed",null,{target:this,async:!1})}),Wn.set(this,()=>{$e(this,ar,"f").fire("paused",null,{target:this,async:!1})}),Yn.set(this,void 0),Hn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Xn.set(this,void 0),zn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,qn.set(this,void 0),Kn.set(this,!0),Zn.set(this,void 0),Jn.set(this,void 0),$n.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},Qn.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle($e(this,Un,"f")).objectFit,s=this.getResolution(),o=$e(this,Un,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=$e(this,Un,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},tr.set(this,!1),er.set(this,()=>{Qe(this,tr,!0,"f")}),ir.set(this,async t=>{var e;if($e(this,tr,"f"))return void Qe(this,tr,!1,"f");if(!$e(this,Qn,"f"))return;if(!this.isVideoPlaying)return;if(!$e(this,Vn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Pr._onLog&&(c=Date.now());try{await $e(this,jn,"m",Sr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Pr._onLog)throw Pr._onLog(t),t}Pr._onLog&&Pr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Pr._onLog&&Pr._onLog("Back to continuous focus."),null===(t=$e(this,Vn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),$e(this,ar,"f").fire("tapfocus",null,{target:this,async:!1})}),nr.set(this,null),rr.set(this,1),sr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!$e(this,Un,"f"))return;const t=$e(this,rr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)$e(this,Un,"f").style.transform="";else{const e=window.getComputedStyle($e(this,Un,"f")).objectFit,i=$e(this,Un,"f").videoWidth,n=$e(this,Un,"f").videoHeight,{width:r,height:s}=$e(this,Un,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-$e(this,sr,"f").x),c=h*(1-1/t)*(n/2-$e(this,sr,"f").y);$e(this,Un,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},or.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===ui.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Pr._onLog&&Pr._onLog("document visible. video paused: "+(null===(t=$e(this,Un,"f"))||void 0===t?void 0:t.paused)),function(){const t=navigator.userAgent||navigator.vendor||navigator.opera;return!!/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(t)||("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024}())"opened"===this.state&&await $e(this,jn,"m",yr).call(this);else if("opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Pr._onLog&&Pr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Pr._onLog&&Pr._onLog("document visible. 1st resume video failed, try open instead.")}e||await $e(this,jn,"m",_r).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Pr._onLog&&Pr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Pr._onLog&&Pr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await $e(this,jn,"m",_r).call(this)}}}else"hidden"===document.visibilityState&&(Pr._onLog&&Pr._onLog("document hidden. video paused: "+(null===(e=$e(this,Un,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),dr.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(()=>{Pr.onWarning&&Pr.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),Qe(this,ar,new Hi,"f"),this.imageDataGetter=new Mr,document.addEventListener("visibilitychange",$e(this,ur,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",$e(this,Gn,"f")),t.addEventListener("pause",$e(this,Wn,"f")),Qe(this,Un,t,"f")}getVideoEl(){return $e(this,Un,"f")}releaseVideoEl(){var t,e;null===(t=$e(this,Un,"f"))||void 0===t||t.removeEventListener("play",$e(this,Gn,"f")),null===(e=$e(this,Un,"f"))||void 0===e||e.removeEventListener("pause",$e(this,Wn,"f")),Qe(this,Un,null,"f")}isVideoLoaded(){return!!$e(this,Un,"f")&&(this.videoSrc?0!==$e(this,Un,"f").readyState:4===$e(this,Un,"f").readyState)}async open(){if($e(this,Zn,"f")&&!$e(this,Kn,"f")){if("pending"===$e(this,Jn,"f"))return $e(this,Zn,"f");if("fulfilled"===$e(this,Jn,"f"))return}$e(this,ar,"f").fire("before:open",null,{target:this}),await $e(this,jn,"m",yr).call(this),$e(this,ar,"f").fire("played",null,{target:this,async:!1}),$e(this,ar,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;$e(this,ar,"f").fire("before:close",null,{target:this});const t=$e(this,Zn,"f");if($e(this,jn,"m",wr).call(this),t&&"pending"===$e(this,Jn,"f")){try{await t}catch(t){}if(!1===$e(this,Kn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Qe(this,Zn,null,"f"),Qe(this,Jn,null,"f"),$e(this,ar,"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.");$e(this,Un,"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 $e(this,Un,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof $e(this,Yn,"f").video&&($e(this,Yn,"f").video={}),delete $e(this,Yn,"f").video.facingMode,$e(this,Yn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&$e(this,Kn,"f"))){$e(this,ar,"f").fire("before:camera:change",[],{target:this,async:!1}),await $e(this,jn,"m",vr).call(this);try{this.resetSoftwareScale()}catch(t){}return $e(this,Hn,"f")}}async switchToFrontCamera(t){if("object"!=typeof $e(this,Yn,"f").video&&($e(this,Yn,"f").video={}),(null==t?void 0:t.resolution)&&($e(this,Yn,"f").video.width={ideal:t.resolution.width},$e(this,Yn,"f").video.height={ideal:t.resolution.height}),delete $e(this,Yn,"f").video.deviceId,$e(this,Yn,"f").video.facingMode={exact:"user"},Qe(this,Xn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&$e(this,Kn,"f"))){$e(this,ar,"f").fire("before:camera:change",[],{target:this,async:!1}),$e(this,jn,"m",vr).call(this);try{this.resetSoftwareScale()}catch(t){}return $e(this,Hn,"f")}}getCamera(){var t;if($e(this,Hn,"f"))return $e(this,Hn,"f");{let e=(null===(t=$e(this,Yn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"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 $e(this,Yn,"f").video&&($e(this,Yn,"f").video={}),i?($e(this,Yn,"f").video.width={exact:t},$e(this,Yn,"f").video.height={exact:e}):($e(this,Yn,"f").video.width={ideal:t},$e(this,Yn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&$e(this,Kn,"f"))return null;$e(this,ar,"f").fire("before:resolution:change",[],{target:this,async:!1}),await $e(this,jn,"m",vr).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&$e(this,Un,"f"))return{width:$e(this,Un,"f").videoWidth,height:$e(this,Un,"f").videoHeight};if($e(this,Vn,"f")){const t=$e(this,Vn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:$e(this,Un,"f").videoWidth,height:$e(this,Un,"f").videoHeight};{const t={width:0,height:0};let e=$e(this,Yn,"f").video.width||0,i=$e(this,Yn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=$e(this,lr,"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=$e(this,Hn,"f"))||void 0===u?void 0:u.deviceId;let e=$e(this,lr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],$e(this,lr,"f").set(d,e),Qe(this,$n,!0,"f");try{for(let t of this.detectedResolutions){await $e(this,Vn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),$e(this,jn,"m",gr).call(this);const i=$e(this,Vn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw $e(this,jn,"m",wr).call(this),Qe(this,$n,!1,"f"),t}try{await $e(this,jn,"m",_r).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Qe(this,$n,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=$e(this,Yn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=$e(this,Yn,"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=$e(this,Yn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=$e(this,lr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],$e(this,lr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Qe(this,Yn,JSON.parse(JSON.stringify(t)),"f"),Qe(this,Xn,null,"f"),e&&await $e(this,jn,"m",vr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify($e(this,Yn,"f")))}resetMediaStreamConstraints(){Qe(this,Yn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return $e(this,Vn,"f").getCapabilities?$e(this,Vn,"f").getCapabilities():{}}getCameraSettings(){if(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return $e(this,Vn,"f").getSettings()}async turnOnTorch(){if(!$e(this,Vn,"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 $e(this,Vn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!$e(this,Vn,"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 $e(this,Vn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Fr(t,n.min,n.step,n.max)),await $e(this,Vn,"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(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Fr(t,n.min,n.step,n.max)),await $e(this,Vn,"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(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await $e(this,Vn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Fr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await $e(this,Vn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await $e(this,jn,"m",Sr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await $e(this,Vn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}enableTapToFocus(){Qe(this,Qn,!0,"f")}disableTapToFocus(){Qe(this,Qn,!1,"f")}isTapToFocusEnabled(){return $e(this,Qn,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"===this.state){t.centerPoint?$e(this,jn,"m",br).call(this,t.centerPoint):this.resetScaleCenter();try{if($e(this,jn,"m",Tr).call(this,$e(this,sr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}else this._zoomPreSetting=t}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*$e(this,rr,"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(!$e(this,Vn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Fr(t,n.min,n.step,n.max)),await $e(this,Vn,"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&&$e(this,jn,"m",br).call(this,e),Qe(this,rr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return $e(this,rr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Qe(this,sr,{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($e(this,$n,"f"))return null;const e=Date.now();Pr._onLog&&Pr._onLog("getFrameData() START: "+e);const i=$e(this,Un,"f").videoWidth,n=$e(this,Un,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=ui.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=$e(this,rr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=$e(this,sr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData($e(this,Un,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Pr._onLog&&Pr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:$e(this,or,"f")}}on(t,e){if(!$e(this,hr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);$e(this,ar,"f").on(t,e)}off(t,e){$e(this,ar,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),$e(this,ar,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",$e(this,ur,"f")),Qe(this,dr,!0,"f")}}var kr,Nr,Br,jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s;Un=new WeakMap,Vn=new WeakMap,Gn=new WeakMap,Wn=new WeakMap,Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,jn=new WeakSet,fr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if($e(this,Xn,"f"))delete t.video.facingMode,t.video.deviceId={exact:$e(this,Xn,"f")};else if(this.ifSaveLastUsedCamera&&Pr.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(Je.OS)?(await this._getCameras(!1),$e(this,jn,"m",gr).call(this),e=Pr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Je.OS)||(await this._getCameras(!1),$e(this,jn,"m",gr).call(this),e=Pr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},gr=function(){if($e(this,Kn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},mr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Pr._onLog&&Pr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise(t=>setTimeout(t,r)),$e(this,jn,"m",gr).call(this));try{Pr._onLog&&Pr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),$e(this,jn,"m",gr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Pr._onLog&&Pr._onLog(t.message||t)}}};if(await r(t),!n&&"object"==typeof t.video&&!n){const e=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let i of e)try{n=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:i.deviceId}}});break}catch(t){continue}}if(!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach(t=>{t.stop()}),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},pr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),Qe(this,Vn,null,"f")},_r=async function(){Qe(this,Kn,!1,"f");const t=Qe(this,qn,Symbol(),"f");if($e(this,Zn,"f")&&"pending"===$e(this,Jn,"f")){try{await $e(this,Zn,"f")}catch(t){}$e(this,jn,"m",gr).call(this)}if(t!==$e(this,qn,"f"))return;const e=Qe(this,Zn,(async()=>{Qe(this,Jn,"pending","f");try{if(this.videoSrc){if(!$e(this,Un,"f"))throw new Error("'videoEl' should be set.");await Pr.playVideo($e(this,Un,"f"),this.videoSrc,this.cameraOpenTimeout),$e(this,jn,"m",gr).call(this)}else{let t=await $e(this,jn,"m",fr).call(this);$e(this,jn,"m",pr).call(this);let e=await $e(this,jn,"m",mr).call(this,t);await this._getCameras(!1),$e(this,jn,"m",gr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=$e(this,Yn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!($e(this,Xn,"f")||this.ifSaveLastUsedCamera&&Pr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Pr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:s},e=await $e(this,jn,"m",mr).call(this,t),$e(this,jn,"m",gr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Qe(this,Xn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Pr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",$e(this,Xn,"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))))),$e(this,Un,"f")&&(await Pr.playVideo($e(this,Un,"f"),e,this.cameraOpenTimeout),$e(this,jn,"m",gr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Qe(this,Vn,s[0],"f"),Qe(this,Hn,r,"f")}}catch(t){throw $e(this,jn,"m",wr).call(this),Qe(this,Jn,null,"f"),t}Qe(this,Jn,"fulfilled","f")})(),"f");return e},vr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=$e(this,Hn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await $e(this,jn,"m",_r).call(this);const n=this.getResolution();e&&e!==$e(this,Hn,"f").deviceId&&$e(this,ar,"f").fire("camera:changed",[$e(this,Hn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||$e(this,ar,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),$e(this,ar,"f").fire("played",null,{target:this,async:!1})},yr=async function(){let t=0;for(;Pr._tryToReopenTime>=t++;){try{await $e(this,jn,"m",_r).call(this)}catch(t){await new Promise(t=>setTimeout(t,300));continue}break}},wr=function(){$e(this,jn,"m",pr).call(this),Qe(this,Hn,null,"f"),$e(this,Un,"f")&&($e(this,Un,"f").srcObject=null,this.videoSrc&&($e(this,Un,"f").pause(),$e(this,Un,"f").currentTime=0)),Qe(this,Kn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},Er=async function t(e,i){const n=t=>{if(!$e(this,Vn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){$e(this,Vn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Fr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await $e(this,Vn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise(t=>{setTimeout(t,r)}),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData($e(this,Un,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:ui.RGBA,bufferContainer:d}))return $e(this,jn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await $e(this,jn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await $e(this,jn,"m",Er).call(this,e,c);if(a>h)return await $e(this,jn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await $e(this,jn,"m",t).call(this,e,o,a,c,h);let u=await $e(this,jn,"m",Er).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!==$e(this,rr,"f")){const t=$e(this,rr,"f"),e=$e(this,sr,"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 n=Fr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Fr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Fr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await $e(this,jn,"m",Er).call(this,t,s),a=await $e(this,jn,"m",Er).call(this,t,r),h=await $e(this,jn,"m",Er).call(this,t,n);if(a>h&&ho&&a>o){let e=await $e(this,jn,"m",Er).call(this,t,i);const r=await $e(this,jn,"m",Cr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await $e(this,jn,"m",Cr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},br=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Qe(this,sr,{x:i,y:n},"f")},Tr=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},Pr.browserInfo=Je,Pr._tryToReopenTime=4,Pr.onWarning=null===(Bn=null===window||void 0===window?void 0:window.console)||void 0===Bn?void 0:Bn.warn;class vs{constructor(t){kr.add(this),Nr.set(this,void 0),Br.set(this,0),jr.set(this,void 0),Ur.set(this,0),Vr.set(this,!1),Qe(this,Nr,t,"f")}startCharging(){$e(this,Vr,"f")||(vs._onLog&&vs._onLog("start charging."),$e(this,kr,"m",Wr).call(this),Qe(this,Vr,!0,"f"))}stopCharging(){$e(this,jr,"f")&&clearTimeout($e(this,jr,"f")),$e(this,Vr,"f")&&(vs._onLog&&vs._onLog("stop charging."),Qe(this,Br,Date.now()-$e(this,Ur,"f"),"f"),Qe(this,Vr,!1,"f"))}}Nr=new WeakMap,Br=new WeakMap,jr=new WeakMap,Ur=new WeakMap,Vr=new WeakMap,kr=new WeakSet,Gr=function(){Vt.cfd(1),vs._onLog&&vs._onLog("charge 1.")},Wr=function t(){0==$e(this,Br,"f")&&$e(this,kr,"m",Gr).call(this),Qe(this,Ur,Date.now(),"f"),$e(this,jr,"f")&&clearTimeout($e(this,jr,"f")),Qe(this,jr,setTimeout(()=>{Qe(this,Br,0,"f"),$e(this,kr,"m",t).call(this)},$e(this,Nr,"f")-$e(this,Br,"f")),"f")};class ys{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-$e(this,Yr,"f",zr)<100)){if(Qe(this,Yr,e,"f",zr),$e(this,Yr,"f",Hr).size&&(t=$e(this,Yr,"f",Hr).values().next().value,this.beepSoundSource==t.src?($e(this,Yr,"f",Hr).delete(t),t.play()):t=null),!t)if($e(this,Yr,"f",Xr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{$e(this,Yr,"f",Xr).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,$e(this,Yr,"f",Xr).delete(t),$e(this,Yr,"f",Hr).add(t)})}else $e(this,Yr,"f",qr)||(Qe(this,Yr,!0,"f",qr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&$e(this,Yr,"f",Xr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(ys.vibrateDuration)}}}Yr=ys,Hr={value:new Set},Xr={value:new Set},zr={value:0},qr={value:!1},ys.allowBeep=!0,ys.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",ys.allowVibrate=!0,ys.vibrateDuration=300;const ws=new Map([[ui.GREY,v.IPF_GRAYSCALED],[ui.RGBA,v.IPF_ABGR_8888]]),Es="function"==typeof BigInt?t=>BigInt(t):t=>t,Cs=(Es("0x00"),Es("0xFFFFFFFFFFFFFFFF"),Es("0xFE3BFFFF"),Es("0x003007FF")),Ss=(Es("0x0003F800"),Es("0x1"),Es("0x2"),Es("0x4"),Es("0x8"),Es("0x10"),Es("0x20"),Es("0x40"),Es("0x80"),Es("0x100"),Es("0x200"),Es("0x400"),Es("0x800"),Es("0x1000"),Es("0x2000"),Es("0x4000"),Es("0x8000"),Es("0x10000"),Es("0x20000"),Es("0x00040000"),Es("0x01000000"),Es("0x02000000"),Es("0x04000000")),bs=Es("0x08000000");Es("0x10000000"),Es("0x20000000"),Es("0x40000000"),Es("0x00080000"),Es("0x80000000"),Es("0x100000"),Es("0x200000"),Es("0x400000"),Es("0x800000"),Es("0x1000000000"),Es("0x3F0000000000000"),Es("0x100000000"),Es("0x10000000000000"),Es("0x20000000000000"),Es("0x40000000000000"),Es("0x80000000000000"),Es("0x100000000000000"),Es("0x200000000000000"),Es("0x200000000"),Es("0x400000000"),Es("0x800000000"),Es("0xC00000000"),Es("0x2000000000"),Es("0x4000000000");class Ts extends rt{static set _onLog(t){Qe(Ts,Zr,t,"f",Jr),Pr._onLog=t,vs._onLog=t}static get _onLog(){return $e(Ts,Zr,"f",Jr)}static async detectEnvironment(){return await(async()=>({wasm:ti,worker:ei,getUserMedia:ii,camera:await ni(),browser:Je.browser,version:Je.version,OS:Je.OS}))()}static async testCameraAccess(){const t=await Pr.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 Lr))throw new TypeError("Invalid view.");if(!Ts._isRTU&&(null===(e=Nt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=Nt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await Vt.loadWasm(),await Nt.license.dynamsoft()}const n=new Ts(t);return Ts.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{Ts.onWarning&&Ts.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(()=>{Ts.onWarning&&Ts.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})},0)),n}get isEnableMirroring(){return this._isEnableMirroring}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Qe(this,es,t,"f")}get singleFrameMode(){return $e(this,es,"f")}get _isFetchingStarted(){return $e(this,as,"f")}get disposed(){return $e(this,ds,"f")}constructor(t){if(super(),Kr.add(this),$r.set(this,"closed"),Qr.set(this,void 0),ts.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,es.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},is.set(this,(t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?ui.GREY:ui.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===ui.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:ws.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:gt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:$e(this,ns,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Gi.convert($e(this,ss,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=$e(this,is,"f").call(this,t,t.width,t.height,e);$e(this,Qr,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ns.set(this,function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===v.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(Je.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",()=>{$e(this,us,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("camera:changed",()=>{this.clearBuffer()}),this._on("before:resolution:change",()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("resolution:changed",()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})}),this._on("paused",()=>{$e(this,us,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{$e(this,ls,"f").tapToFocus&&$e(this,us,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if($e(this,Kr,"m",fs).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Ts._onLog&&(Ts._onLog("intermediateResultUnits:"),Ts._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===vt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===vt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Ts._onLog&&(Ts._onLog("hasLocalizedBarcodes:"),Ts._onLog(h)),$e(this,ls,"f").autoZoom||$e(this,ls,"f").enhancedFocus)if(a)$e(this,cs,"f").autoZoomInFrameArray.length=0,$e(this,cs,"f").autoZoomOutFrameCount=0,$e(this,cs,"f").frameArrayInIdealZoom.length=0,$e(this,cs,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),$e(this,ls,"f").autoZoom&&$e(this,us,"f").startCharging()},a=async t=>{await this.setFocus(t),$e(this,ls,"f").enhancedFocus&&$e(this,us,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-$e(this,cs,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+$e(this,cs,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-$e(this,cs,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+$e(this,cs,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Ts._onLog&&(Ts._onLog("detectionArea:"),Ts._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=zi(a.y-i)>0&&zi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(qi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||qi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||qi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||qi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===vt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Lr._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Ts._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Ir.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===vt.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Li({points:i},e);t.addDrawingItems([r])}}}if(Ts._onLog&&(Ts._onLog("intersectedResults:"),Ts._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==Ss||t.possibleFormats==bs);if(t.length||(t=s.filter(t=>t.possibleFormats==Cs),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize<$e(this,cs,"f").autoZoomInIdealModuleSize){if($e(this,cs,"f").autoZoomInFrameArray.push(!0),$e(this,cs,"f").autoZoomInFrameArray.splice(0,$e(this,cs,"f").autoZoomInFrameArray.length-$e(this,cs,"f").autoZoomInFrameLimit[0]),$e(this,cs,"f").frameArrayInIdealZoom.length=0,$e(this,ls,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{}),$e(this,cs,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=$e(this,cs,"f").autoZoomInFrameLimit[1]){$e(this,cs,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,$e(this,cs,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/$e(this,cs,"f").autoZoomInMaxTimes),$e(this,cs,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max($e(this,cs,"f").minValue,u),u=Math.min($e(this,cs,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if($e(this,cs,"f").autoZoomInFrameArray.length=0,$e(this,cs,"f").frameArrayInIdealZoom.push(!0),$e(this,cs,"f").frameArrayInIdealZoom.splice(0,$e(this,cs,"f").frameArrayInIdealZoom.length-$e(this,cs,"f").frameLimitInIdealZoom[0]),$e(this,cs,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=$e(this,cs,"f").frameLimitInIdealZoom[1]&&($e(this,cs,"f").frameArrayInIdealZoom.length=0,$e(this,ls,"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(!$e(this,ls,"f").autoZoom&&$e(this,ls,"f").enhancedFocus&&($e(this,cs,"f").autoFocusFrameArray.push(!0),$e(this,cs,"f").autoFocusFrameArray.splice(0,$e(this,cs,"f").autoFocusFrameArray.length-$e(this,cs,"f").autoFocusFrameLimit[0]),$e(this,cs,"f").autoFocusFrameArray.filter(t=>!0===t).length>=$e(this,cs,"f").autoFocusFrameLimit[1])){$e(this,cs,"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($e(this,ls,"f").autoZoom){if($e(this,cs,"f").autoZoomInFrameArray.push(!1),$e(this,cs,"f").autoZoomInFrameArray.splice(0,$e(this,cs,"f").autoZoomInFrameArray.length-$e(this,cs,"f").autoZoomInFrameLimit[0]),$e(this,cs,"f").autoZoomOutFrameCount++,$e(this,cs,"f").frameArrayInIdealZoom.push(!1),$e(this,cs,"f").frameArrayInIdealZoom.splice(0,$e(this,cs,"f").frameArrayInIdealZoom.length-$e(this,cs,"f").frameLimitInIdealZoom[0]),$e(this,cs,"f").autoZoomOutFrameCount>=$e(this,cs,"f").autoZoomOutFrameLimit){$e(this,cs,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*$e(this,cs,"f").autoZoomOutStepRate,$e(this,cs,"f").autoZoomOutMinStep);n=Math.max($e(this,cs,"f").minValue,n),n=Math.min($e(this,cs,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}$e(this,ls,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!$e(this,ls,"f").autoZoom&&$e(this,ls,"f").enhancedFocus&&($e(this,cs,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},Qe(this,us,new vs(1e4),"f"),this.getColourChannelUsageType()===_.CCUT_AUTO&&this.setColourChannelUsageType(_.CCUT_Y_CHANNEL_ONLY),this.setPixelFormat(v.IPF_GRAYSCALED)}setCameraView(t){if(!(t instanceof Lr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),$e(this,Kr,"m",fs).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;$e(this,Kr,"m",fs).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return $e(this,Kr,"m",fs).call(this)?$e(this,$r,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,$e(this,Kr,"m",fs).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if($e(this,Kr,"m",fs).call(this));else{try{await this.cameraManager.open(),Qe(this,ts,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=ys.allowBeep?"":"none"),a&&(a.style.display=ys.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=ys.allowVibrate?"":"none"),l&&(l.style.display=ys.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const E=()=>{ys.allowBeep=!ys.allowBeep,o&&(o.style.display=ys.allowBeep?"":"none"),a&&(a.style.display=ys.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",E);const C=()=>{ys.allowVibrate=!ys.allowVibrate,h&&(h.style.display=ys.allowVibrate?"":"none"),l&&(l.style.display=ys.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",C);const S=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==Je?void 0:Je.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",E);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",C);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return Qe(this,$r,"open","f"),e&&(e._innerComponent.style.display="",$e(this,Kr,"m",fs).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),$e(this,Qr,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),$e(this,Kr,"m",fs).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Qe(this,$r,"closed","f"),$e(this,us,"f").stopCharging(),e&&(e._innerComponent.style.display="none",$e(this,Kr,"m",fs).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),$e(this,Qr,"f").fire("closed",null,{target:this,async:!1})}pause(){if($e(this,Kr,"m",fs).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!$e(this,Kr,"m",fs).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if($e(this,Kr,"m",fs).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch(()=>{});const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),this.toggleMirroring(this._isEnableMirroring),$e(this,ss,"f")&&this.setScanRegion($e(this,ss,"f")),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?$e(this,Qr,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?$e(this,Qr,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if($e(this,Kr,"m",fs).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if($e(this,Kr,"m",fs).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(v.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Ts._onLog)||void 0===t||t.call(Ts,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if($e(this,Kr,"m",fs).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if($e(this,Kr,"m",fs).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if($e(this,Kr,"m",fs).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if($e(this,Kr,"m",fs).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if($e(this,Kr,"m",fs).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if($e(this,Kr,"m",fs).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){$e(this,cs,"f").minValue=t.min,$e(this,cs,"f").maxValue=t.max}getAutoZoomRange(){return{min:$e(this,cs,"f").minValue,max:$e(this,cs,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=Nt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==Vt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ci.EF_ENHANCED_FOCUS&&($e(this,ls,"f").enhancedFocus=!0),t&ci.EF_AUTO_ZOOM&&($e(this,ls,"f").autoZoom=!0),t&ci.EF_TAP_TO_FOCUS&&($e(this,ls,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ci.EF_ENHANCED_FOCUS&&($e(this,ls,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&ci.EF_AUTO_ZOOM&&($e(this,ls,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&ci.EF_TAP_TO_FOCUS&&($e(this,ls,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),$e(this,Kr,"m",ms).call(this)&&$e(this,Kr,"m",gs).call(this)||$e(this,us,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!R(t)&&!P(t))throw TypeError("Invalid 'region'.");Qe(this,ss,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify($e(this,ss,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Qe(this,rs,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||$e(this,Kr,"m",fs).call(this))}startFetching(){if($e(this,Kr,"m",fs).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");$e(this,as,"f")||(Qe(this,as,!0,"f"),$e(this,Kr,"m",ps).call(this))}stopFetching(){$e(this,as,"f")&&(Ts._onLog&&Ts._onLog("DCE: stop fetching loop: "+Date.now()),$e(this,hs,"f")&&clearTimeout($e(this,hs,"f")),Qe(this,as,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if($e(this,Kr,"m",fs).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i,n;if(i=Gi.convert($e(this,ss,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");if(i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y),$e(this,ss,"f")&&!t)n={sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};else{const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});n={sx:t.x,sy:t.y,sWidth:t.width,sHeight:t.height,dWidth:t.width,dHeight:t.height}}const r=Math.max(n.dWidth,n.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;n.dWidth>n.dHeight?(n.dWidth=this.canvasSizeLimit,n.dHeight=Math.round(n.dHeight*t)):(n.dWidth=Math.round(n.dWidth*t),n.dHeight=this.canvasSizeLimit)}const s=this.cameraManager.getFrameData({position:n,pixelFormat:this.getPixelFormat()===v.IPF_GRAYSCALED?ui.GREY:ui.RGBA,isEnableMirroring:this._isEnableMirroring});if(!s)return null;let o;o=s.pixelFormat===ui.GREY?s.width:4*s.width;let a=!0;return 0===n.sx&&0===n.sy&&n.sWidth===e.width&&n.sHeight===e.height&&(a=!1),{bytes:s.data,width:s.width,height:s.height,stride:o,format:ws.get(s.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:gt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:n.sx,top:n.sy,right:n.sx+n.sWidth,bottom:n.sy+n.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:s.width,currentHeight:s.height,timeSpent:s.timeSpent,timeStamp:s.timeStamp},toCanvas:$e(this,ns,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,$e(this,as,"f")&&($e(this,hs,"f")&&clearTimeout($e(this,hs,"f")),Qe(this,hs,setTimeout(()=>{this.disposed||$e(this,Kr,"m",ps).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Qe(this,os,t,"f")}getPixelFormat(){return $e(this,os,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if($e(this,Kr,"m",fs).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",()=>{t&&this.open(),e.remove()},{once:!0})}),e.addEventListener("change",async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=Gi.convert($e(this,ss,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=$e(this,is,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=this.convertToContainCoordinates(t),i=$e(this,Kr,"m",_s).call(this,e);return{x:i.pageX,y:i.pageY}}convertToClientCoordinates(t){const e=this.convertToContainCoordinates(t),i=$e(this,Kr,"m",_s).call(this,e);return{x:i.clientX,y:i.clientY}}convertToScanRegionCoordinates(t){if(!$e(this,ss,"f"))return JSON.parse(JSON.stringify(t));const e=this.convertToContainCoordinates(t);if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});Qe(this,ts,t||$e(this,ts,"f"),"f")}let i,n,r=$e(this,ss,"f").left||$e(this,ss,"f").x||0,s=$e(this,ss,"f").top||$e(this,ss,"f").y||0;if(!$e(this,ss,"f").isMeasuredInPercentage)return{x:e.x-(r+$e(this,ts,"f").x),y:e.y-(s+$e(this,ts,"f").y)};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!$e(this,Kr,"m",fs).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if($e(this,Kr,"m",fs).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if($e(this,Kr,"m",fs).call(this)){const t=this.cameraView._innerComponent.getElement("content");i=t.width,n=t.height}else i=$e(this,ts,"f").width,n=$e(this,ts,"f").height;return{x:e.x-(Math.round(r*i/100)+$e(this,ts,"f").x),y:e.y-(Math.round(s*n/100)+$e(this,ts,"f").y)}}convertToContainCoordinates(t){if("contain"===this.cameraView.getVideoFit())return t;const e=this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),i=JSON.parse(JSON.stringify(t));return R($e(this,ss,"f"))?$e(this,ss,"f").isMeasuredInPercentage?(i.x=e.width*($e(this,ss,"f").left/100)+e.x+t.x,i.y=e.height*($e(this,ss,"f").top/100)+e.y+t.y):(i.x=$e(this,ss,"f").left+e.x+t.x,i.y=$e(this,ss,"f").top+e.y+t.y):$e(this,ss,"f").isMeasuredInPercentage?(i.x=e.width*($e(this,ss,"f").x/100)+e.x+t.x,i.y=e.height*($e(this,ss,"f").y/100)+e.y+t.y):(i.x=$e(this,ss,"f").x+e.x+t.x,i.y=$e(this,ss,"f").y+e.y+t.y),i}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Qe(this,ds,!0,"f")}}var Is,xs,Os,Rs,As,Ds,Ls,Ms;Zr=Ts,$r=new WeakMap,Qr=new WeakMap,ts=new WeakMap,es=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,Kr=new WeakSet,fs=function(){return"disabled"!==this.singleFrameMode},gs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},ms=function(){for(let t in $e(this,ls,"f"))if(1==$e(this,ls,"f")[t])return!0;return!1},ps=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!$e(this,as,"f"))return $e(this,hs,"f")&&clearTimeout($e(this,hs,"f")),void Qe(this,hs,setTimeout(()=>{this.disposed||$e(this,Kr,"m",t).call(this)},this.fetchInterval),"f");const e=()=>{var t;let e;Ts._onLog&&Ts._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=$e(this,rs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=$e(this,rs,"f"))||void 0===t||t.onErrorReceived(ut.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),Ts._onLog&&Ts._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),$e(this,Qr,"f").fire("frameAddedToBuffer",null,{async:!1})):Ts._onLog&&Ts._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case p.BOPM_BLOCK:break;case p.BOPM_UPDATE:e()}else e();$e(this,hs,"f")&&clearTimeout($e(this,hs,"f")),Qe(this,hs,setTimeout(()=>{this.disposed||$e(this,Kr,"m",t).call(this)},this.fetchInterval),"f")},_s=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!$e(this,Kr,"m",fs).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if($e(this,Kr,"m",fs).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if($e(this,Kr,"m",fs).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if($e(this,Rs,"f")||Qe(this,Rs,new Fs,"f"),!$e(this,Rs,"f").magnifierCanvas)return;document.body.contains($e(this,Rs,"f").magnifierCanvas)||($e(this,Rs,"f").magnifierCanvas.style.position="fixed",$e(this,Rs,"f").magnifierCanvas.style.boxSizing="content-box",$e(this,Rs,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append($e(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 $e(this,Ds,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];$e(this,Rs,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?($e(this,Rs,"f").magnifierCanvas.style.left="auto",$e(this,Rs,"f").magnifierCanvas.style.top="0",$e(this,Rs,"f").magnifierCanvas.style.right="0"):($e(this,Rs,"f").magnifierCanvas.style.left="0",$e(this,Rs,"f").magnifierCanvas.style.top="0",$e(this,Rs,"f").magnifierCanvas.style.right="auto")}$e(this,Rs,"f").show()}),Ds.set(this,()=>{$e(this,Rs,"f")&&$e(this,Rs,"f").hide()}),Ls.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Ki(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(O(t)){Qe(this,Os,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===v.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2})),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new di.Control({positionHandler:Oi,actionHandler:Di(i>0?i-1:n,Ai),actionName:"modifyPolygon",pointIndex:i}),t},{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=di.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){$e(this,Pi,"f")&&this.setLine($e(this,Pi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!D(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Qe(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 $e(this,Pi,"f")?JSON.parse(JSON.stringify($e(this,Pi,"f"))):null}},QuadDrawingItem:Ni,RectDrawingItem:xi,TextDrawingItem:Fi});const Ns="undefined"==typeof self,Bs=Ns?{}:self,js="function"==typeof importScripts,Us=(()=>{if(!js){if(!Ns&&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"./"}})(),Vs=t=>t&&"object"==typeof t&&"function"==typeof t.then,Gs=(async()=>{})().constructor;let Ws=class extends Gs{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,Vs(t)?e=t:"function"==typeof t&&(e=new Gs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Vs(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ys=" is not allowed to change after `createInstance` or `loadWasm` is called.",Hs=!Ns&&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"))||"",Xs=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ys);i._license=e}};!Ns&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const zs=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=zs(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ys);i._licenseServer=e}},Ks=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ys);i._deviceFriendlyName=e}};let Zs,Js,$s,Qs,to;"undefined"!=typeof navigator&&(Zs=navigator,Js=Zs.userAgent,$s=Zs.platform,Qs=Zs.mediaDevices),function(){if(!Ns){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Zs.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:$s,search:"Win"},Mac:{str:$s},Linux:{str:$s}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Js,o=r.search||e,a=r.verStr||Js,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Js,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Js.indexOf("Windows NT")&&(r="HarmonyOS"),to={browser:i,version:n,OS:r}}Ns&&(to={browser:"ssr",version:0,OS:"ssr"})}(),Qs&&Qs.getUserMedia,"Chrome"===to.browser&&to.version>66||"Safari"===to.browser&&to.version>13||"OPR"===to.browser&&to.version>43||"Edge"===to.browser&&to.version;const eo=()=>(Vt.loadWasm(),xt("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=zs(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Bs.crypto||(s="Please upgrade your browser to support online key."),Bs.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Ys)})(no),o=new Ws;no._pLoad.task=o,(async()=>{try{await no._pLoad}catch(t){}})();let a=At();Dt[a]=e=>{if(e.message&&no._onAuthMessage){let t=no._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(Lt&&Lt("init license success"),e.message&&console.warn(e.message),Vt._bSupportIRTModule=e.bSupportIRTModule,Vt._bSupportDce4Module=e.bSupportDce4Module,no.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=B(Vt.engineResourcePaths),i=("DCV"===Vt._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:no._bNeverShowDialog,engineResourcePath:i,_onLog:Lt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await It("core");const h=await Vt.getModuleVersion();Ot.postMessage({type:"license_dynamsoft",body:{v:"DCV"===Vt._bundleEnv?h.CVR.replace(/\.\d+$/,""):h.DBR.replace(/\.\d+$/,""),brtk:!!t,bptk:1===t,l:e,os:to,fn:no.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),no.bCallInitLicense=!0,await o}));let io;Nt.license={},Nt.license.dynamsoft=eo,Nt.license.getAR=async()=>{{let t=Tt.dynamsoft_inited;t&&t.isRejected&&await t}return Ot?new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success){delete i.success;{let t=no.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)}},Ot.postMessage({type:"license_getAR",id:i})}):null};let no=class t{static setLicenseServer(e){qs(t,e)}static get license(){return this._license}static set license(e){Xs(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){qs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Ks(t,e)}static initLicense(e,i){if(Xs(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return eo()}static setDeviceFriendlyName(e){Ks(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await xt("dynamsoft_uuid",async()=>{await Vt.loadWasm();let t=new Ws,e=At();Dt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Ot.postMessage({type:"license_getDeviceUUID",id:e}),io=await t}),io))()}};no._pLoad=new Ws,no.bPassValidation=!1,no.bCallInitLicense=!1,no._license=Hs,no._licenseServer=[],no._deviceFriendlyName="",Vt.engineResourcePaths.license={version:"4.2.20-dev-20251029130543",path:Us,isInternal:!0},Bt.license={wasm:!0,js:!0},Nt.license.LicenseManager=no;const ro="2.0.0";"string"!=typeof Vt.engineResourcePaths.std&&N(Vt.engineResourcePaths.std.version,ro)<0&&(Vt.engineResourcePaths.std={version:ro,path:(t=>{if(null==t&&(t="./"),Ns||js);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Us+`../../dynamsoft-capture-vision-std@${ro}/dist/`),isInternal:!0});var so=Object.freeze({__proto__:null,LicenseManager:no,LicenseModule:class{static getVersion(){return`4.2.20-dev-20251029130543(Worker: ${kt.license&&kt.license.worker||"Not Loaded"}, Wasm: ${kt.license&&kt.license.wasm||"Not Loaded"})`}}});const oo=()=>window.matchMedia("(orientation: landscape)").matches,ao=t=>Object.prototype.toString.call(t).slice(8,-1);function ho(t,e){for(const i in e)"Object"===ao(e[i])&&i in t?ho(t[i],e[i]):t[i]=e[i];return t}function lo(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function co(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;ie.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const fo="undefined"==typeof self,go="function"==typeof importScripts,mo=(()=>{if(!go){if(!fo&&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"./"}})(),po=t=>{if(null==t&&(t="./"),fo||go);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Vt.engineResourcePaths.utility={version:"2.2.20-dev-20251029130550",path:mo,isInternal:!0},Bt.utility={js:!0,wasm:!0};const _o="2.0.0";"string"!=typeof Vt.engineResourcePaths.std&&N(Vt.engineResourcePaths.std.version,_o)<0&&(Vt.engineResourcePaths.std={version:_o,path:po(mo+`../../dynamsoft-capture-vision-std@${_o}/dist/`),isInternal:!0});const vo="3.0.10";(!Vt.engineResourcePaths.dip||"string"!=typeof Vt.engineResourcePaths.dip&&N(Vt.engineResourcePaths.dip.version,vo)<0)&&(Vt.engineResourcePaths.dip={version:vo,path:po(mo+`../../dynamsoft-image-processing@${vo}/dist/`),isInternal:!0});function yo(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const wo="undefined"==typeof self,Eo="function"==typeof importScripts,Co=(()=>{if(!Eo){if(!wo&&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"./"}})(),So=t=>{if(null==t&&(t="./"),wo||Eo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Vt.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:Co,isInternal:!0},Bt.dbr={js:!1,wasm:!0,deps:[St.MN_DYNAMSOFT_LICENSE,St.MN_DYNAMSOFT_IMAGE_PROCESSING]},Nt.dbr={};const bo="2.0.0";"string"!=typeof Vt.engineResourcePaths.std&&N(Vt.engineResourcePaths.std.version,bo)<0&&(Vt.engineResourcePaths.std={version:bo,path:So(Co+`../../dynamsoft-capture-vision-std@${bo}/dist/`),isInternal:!0});const To="3.0.10";(!Vt.engineResourcePaths.dip||"string"!=typeof Vt.engineResourcePaths.dip&&N(Vt.engineResourcePaths.dip.version,To)<0)&&(Vt.engineResourcePaths.dip={version:To,path:So(Co+`../../dynamsoft-image-processing@${To}/dist/`),isInternal:!0});const Io={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var xo,Oo,Ro,Ao,Do;(Do=xo||(xo={}))[Do.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",Do[Do.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",Do[Do.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Oo||(Oo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(Ro||(Ro={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(Ao||(Ao={}));const Lo=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:v.IPF_ABGR_8888}};function Mo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function ko(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function jo(t){let e=0;for(let i=0;i0}function Vo(t,e){for(let i=0;i<4;i++)if(!Uo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}function Go(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=ko(r)[3],h=ko(r)[1],l=ko(s)[3],c=ko(s)[1];let u,d=0;if(u=Math.max(Math.abs(Po(a,e.points[0])),Math.abs(Po(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(h,e.points[1])),Math.abs(Po(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Po(l,t.points[0])),Math.abs(Po(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Po(c,t.points[1])),Math.abs(Po(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=No(ko(r)[0]),g=No(ko(r)[2]),m=No(ko(s)[0]),p=No(ko(s)[2]),_=Fo(f,p),v=Fo(m,g),y=_>v,w=Math.min(_,v),E=Fo(f,g),C=Fo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,E),S=Math.min(S,C),!!(w{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Vo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Vo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Vo(t,this.location.points[e]))return!0;if(Vo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Po(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Bo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{Mo(e,t)&&i.push(t)}),e.forEach(e=>{Mo(t,e)&&i.push(e)}),jo(function(t){if(t.length<=1)return t;t.sort((t,e)=>t.x-e.x||t.y-e.y);const e=t.shift();return t.sort((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x)),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}var Yo,Ho,Xo,zo,qo;const Ko={barcode:2,text_line:4,detected_quad:8,deskewed_image:16,enhanced_image:64},Zo=t=>Object.values(Ko).includes(t)||Ko.hasOwnProperty(t),Jo=(t,e)=>"string"==typeof t?e[Ko[t]]:e[t],$o=(t,e,i)=>{"string"==typeof t?e[Ko[t]]=i:e[t]=i},Qo=(t,e,i)=>{const n=[{type:lt.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:lt.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class ta{constructor(){this.verificationEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!0,[lt.CRIT_DETECTED_QUAD]:!0,[lt.CRIT_DESKEWED_IMAGE]:!1,[lt.CRIT_ENHANCED_IMAGE]:!1},this.duplicateFilterEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!1,[lt.CRIT_DETECTED_QUAD]:!1,[lt.CRIT_DESKEWED_IMAGE]:!1,[lt.CRIT_ENHANCED_IMAGE]:!1},this.duplicateForgetTime={[lt.CRIT_BARCODE]:3e3,[lt.CRIT_TEXT_LINE]:3e3,[lt.CRIT_DETECTED_QUAD]:3e3,[lt.CRIT_DESKEWED_IMAGE]:3e3,[lt.CRIT_ENHANCED_IMAGE]:3e3},Yo.set(this,new Map),Ho.set(this,new Map),Xo.set(this,new Map),zo.set(this,new Map),qo.set(this,new Map),this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,this.latestOverlappingEnabled={[lt.CRIT_BARCODE]:!1,[lt.CRIT_TEXT_LINE]:!1,[lt.CRIT_DETECTED_QUAD]:!1,[lt.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[lt.CRIT_BARCODE]:this.crossVerificationFrames,[lt.CRIT_TEXT_LINE]:this.crossVerificationFrames,[lt.CRIT_DETECTED_QUAD]:this.crossVerificationFrames,[lt.CRIT_DESKEWED_IMAGE]:this.crossVerificationFrames},Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),Qo(this,t,lt.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{Qo(this,t,lt.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){yo(this,Yo,"f").forEach((t,e)=>{$o(e,this.verificationEnabled,t)}),yo(this,Ho,"f").forEach((t,e)=>{$o(e,this.duplicateFilterEnabled,t)}),yo(this,Xo,"f").forEach((t,e)=>{$o(e,this.duplicateForgetTime,t)}),yo(this,zo,"f").forEach((t,e)=>{$o(e,this.latestOverlappingEnabled,t)}),yo(this,qo,"f").forEach((t,e)=>{$o(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){Zo(t)&&yo(this,Yo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Zo(t)&&Jo(t,this.verificationEnabled)}enableResultDeduplication(t,e){Zo(t)&&(e&&this.enableLatestOverlapping(t,!1),yo(this,Ho,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Zo(t)&&Jo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Zo(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),yo(this,Xo,"f").set(t,e))}getDuplicateForgetTime(t){return Zo(t)?Jo(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[lt.CRIT_BARCODE,lt.CRIT_TEXT_LINE,lt.CRIT_DETECTED_QUAD,lt.CRIT_DESKEWED_IMAGE,lt.CRIT_ENHANCED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Io.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Io.BF_GS1_DATABAR))!=BigInt(0);return new Wo(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Io.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Io.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}f.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),d.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}var ea,ia,na,ra;Yo=new WeakMap,Ho=new WeakMap,Xo=new WeakMap,zo=new WeakMap,qo=new WeakMap;class sa{async readFromFile(t){return await Lo(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=W(t);return j(n,e,i)}async readFromMemory(t){if(!yo(sa,ea,"f",ia).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=yo(sa,ea,"f",ia).get(t);return await new Promise((t,n)=>{let r=At();Dt[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Ot.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{var i,n;if(e.success)return function(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");r?r.value=i:e.set(t,i)}(i=sa,ea,(n=yo(i,ea,"f",na),++n),0,na),yo(sa,ea,"f",ia).set(yo(sa,ea,"f",na),JSON.parse(e.memery)),t(yo(sa,ea,"f",na));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Ot.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}ea=sa,ia={value:new Map},na={value:0};!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(ra||(ra={}));var oa,aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ea,Ca,Sa,ba,Ta,Ia,xa,Oa,Ra,Aa,Da,La,Ma,Fa,Pa,ka,Na,Ba=Object.freeze({__proto__:null,get EnumFilterType(){return ra},ImageDrawer:class{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await Lo(t);else if("string"==typeof t){let e=await k(t,"blob");a=await Lo(e)}else O(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=At();Dt[l]=async e=>{if(e.success)return o&&(new sa).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Ot.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}},ImageIO:sa,ImageProcessor:class{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await Lo(t);return await new Promise((t,l)=>{let c=At();Dt[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Ot.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await Lo(t);return await new Promise((t,h)=>{let l=At();Dt[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Ot.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await Lo(t);return await new Promise((t,l)=>{let c=At();Dt[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Ot.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Lo(t);return await new Promise((t,a)=>{let h=At();Dt[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Ot.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}},MultiFrameResultCrossFilter:ta,UtilityModule:class{static getVersion(){return`2.2.20-dev-20251029130550(Worker: ${kt.utility&&kt.utility.worker||"Not Loaded"}, Wasm: ${kt.utility&&kt.utility.wasm||"Not Loaded"})`}}});class ja{constructor(e){if(oa.add(this),la.set(this,void 0),ca.set(this,{status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]}),ua.set(this,!1),da.set(this,void 0),fa.set(this,void 0),ga.set(this,void 0),ma.set(this,void 0),this.config=co(Wt),e&&"object"!=typeof e||Array.isArray(e))throw"Invalid config.";ho(this.config,e),Ts._isRTU=!0}get disposed(){return i(this,ua,"f")}launch(){return e(this,void 0,void 0,function*(){if(i(this,ua,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(i(ja,aa,"f",ha)&&!i(ja,aa,"f",ha).isFulfilled&&!i(ja,aa,"f",ha).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return n(ja,aa,new Xt,"f",ha),i(this,oa,"m",pa).call(this),i(ja,aa,"f",ha)})}decode(t,r="ReadBarcodes_Default"){return e(this,void 0,void 0,function*(){n(this,fa,r,"f"),yield i(this,oa,"m",_a).call(this,!0),i(this,ma,"f")||n(this,ma,new ta,"f"),i(this,ma,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(i(this,ma,"f"));const e=new Ve;e.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(e);const s=yield this._cvRouter.capture(t,r);return i(this,ma,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(i(this,ma,"f")),this._cvRouter.removeResultReceiver(e),s})}dispose(){var t,e,r,s,o,a,h;n(this,ua,!0,"f"),i(ja,aa,"f",ha)&&i(ja,aa,"f",ha).isPending&&i(ja,aa,"f",ha).resolve(i(this,ca,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(e=this._cameraView)||void 0===e||e.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",i(this,la,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}aa=ja,la=new WeakMap,ca=new WeakMap,ua=new WeakMap,da=new WeakMap,fa=new WeakMap,ga=new WeakMap,ma=new WeakMap,oa=new WeakSet,pa=function(){return e(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield i(this,oa,"m",_a).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),lo(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){i(this,oa,"m",Fa).call(this,document.querySelector(".btn-upload-image"),!0),i(this,oa,"m",Pa).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(i(this,fa,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(e){i(this,ca,"f").status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(ja,aa,"f",ha).reject(new Error(i(this,ca,"f").status.message)),this.dispose()}finally{i(this,oa,"m",ka).call(this,"Loading...",!1)}})},_a=function(r=!1){return e(this,void 0,void 0,function*(){if(Vt.engineResourcePaths=this.config.engineResourcePaths,!r){const e=B(Vt.engineResourcePaths);if(this._cameraView=yield Lr.createInstance(e.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this._cameraView._createDrawingLayer(2),this.config.scanMode===t.EnumScanMode.SM_SINGLE||this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1)}if(this._cameraEnhancer=yield Ts.createInstance(this._cameraView),this.disposed)return;if(yield i(this,oa,"m",ya).call(this),this.disposed)return;this.config.scannerViewConfig.customHighlightForBarcode&&n(this,ga,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}yield no.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield Ue.createInstance()),this.disposed||(this.config.scanMode!==t.EnumScanMode.SM_SINGLE||r?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{i(ja,aa,"f",ha).reject(new Error(t.message)),this.dispose()},yield i(this,oa,"m",va).call(this,r),this.disposed||r||(this._cvRouter.setInput(this._cameraEnhancer),i(this,oa,"m",xa).call(this),yield i(this,oa,"m",Oa).call(this),this.disposed)))})},va=function(r=!1){return e(this,void 0,void 0,function*(){if(r||(this.config.scanMode===t.EnumScanMode.SM_SINGLE?n(this,fa,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&n(this,fa,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const e=yield this._cvRouter.getSimplifiedSettings(i(this,fa,"f"));if(this.disposed)return;r||this.config.scanMode!==t.EnumScanMode.SM_SINGLE||(e.outputOriginalImage=!0);let s=this.config.barcodeFormats;if(s){Array.isArray(s)||(s=[s]),e.barcodeSettings.barcodeFormatIds=BigInt(0);for(let t=0;t{document.head.appendChild(t.cloneNode(!0))}),this.config.scanMode===t.EnumScanMode.SM_SINGLE){const t=document.createElement("style");t.innerText="@keyframes result-option-flash {\n from {transform: translate(-50%, -50%) scale(1);}\n to {transform: translate(-50%, -50%) scale(0.8);}\n }";this._cameraView.getUIElement().shadowRoot.append(t)}n(this,da,o.querySelector(".result-item"),"f"),i(this,oa,"m",wa).call(this,o),i(this,oa,"m",Ea).call(this,o),i(this,oa,"m",Ca).call(this,o),i(this,oa,"m",Sa).call(this,o),yield i(this,oa,"m",ba).call(this,o),i(this,oa,"m",Fa).call(this,o.querySelector(".btn-upload-image"),this.config.showUploadImageButton),i(this,oa,"m",Ia).call(this,o),i(this,oa,"m",Ta).call(this,o)})},wa=function(t){var e,n,r;const s=t.querySelector(".btn-clear");if(s&&(s.addEventListener("click",()=>{i(this,ca,"f").barcodeResults=[],i(this,oa,"m",La).call(this)}),null===(r=null===(n=null===(e=this.config)||void 0===e?void 0:e.resultViewConfig)||void 0===n?void 0:n.toolbarButtonsConfig)||void 0===r?void 0:r.clear)){const e=this.config.resultViewConfig.toolbarButtonsConfig.clear;s.style.display=e.isHidden?"none":"flex",s.className=e.className?e.className:"btn-clear",s.innerText=e.label?e.label:"Clear",e.isHidden&&(t.querySelector(".toolbar-btns").style.justifyContent="center")}},Ea=function(t){var e,i,n;const r=t.querySelector(".btn-done");if(r&&(r.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(n=null===(i=null===(e=this.config)||void 0===e?void 0:e.resultViewConfig)||void 0===i?void 0:i.toolbarButtonsConfig)||void 0===n?void 0:n.done)){const e=this.config.resultViewConfig.toolbarButtonsConfig.done;r.style.display=e.isHidden?"none":"flex",r.className=e.className?e.className:"btn-done",r.innerText=e.label?e.label:"Done",e.isHidden&&(t.querySelector(".toolbar-btns").style.justifyContent="center")}},Ca=function(e){var n,r;if(null===(r=null===(n=this.config)||void 0===n?void 0:n.scannerViewConfig)||void 0===r?void 0:r.showCloseButton){const n=e.querySelector(".btn-close");n&&(n.style.display="",n.addEventListener("click",()=>{i(this,ca,"f").barcodeResults=[],i(this,ca,"f").status={code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}},Sa=function(t){var n;if(null===(n=this.config)||void 0===n?void 0:n.scannerViewConfig.showFlashButton){const n=t.querySelector(".btn-flash-auto"),r=t.querySelector(".btn-flash-open"),s=t.querySelector(".btn-flash-close");if(n){n.style.display="";let t=null,o=250,a=20,h=3;const l=(l=250)=>e(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==t){if(!(le(this,void 0,void 0,function*(){var e;if(i(this,ua,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(t),void(t=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(t),t=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(v.IPF_GRAYSCALED===l.format){for(let t=0;t=h){null===(e=Ts._onLog)||void 0===e||e.call(Ts,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,n.style.display="none",r.style.display="",s.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});t=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&i(this,oa,"m",Pa).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),n.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),n.style.display="none",r.style.display="",s.style.display="none"})),r.addEventListener("click",()=>e(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),n.style.display="none",r.style.display="none",s.style.display=""})),s.addEventListener("click",()=>e(this,void 0,void 0,function*(){l(1e3),n.style.display="",r.style.display="none",s.style.display="none"}))}}},ba=function(t){return e(this,void 0,void 0,function*(){let n=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(n)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const n=t.querySelector(".camera-control");if(n){n.style.display="";const r=yield this._cameraEnhancer.getAllCameras(),s=this.config.scannerViewConfig.cameraSwitchControl,o=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px",cursor:"pointer"}),e},a=()=>{if(0===r.length)return null;if("listAll"===s){const n=t.querySelector(".camera-list");for(let t of r){const e=o(t);n.append(e)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const s=t=>{for(let e of a)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};n.addEventListener("click",t=>e(this,void 0,void 0,function*(){const e=t.target;i(this,oa,"m",ka).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:e.deviceId,label:e.label,_checked:e._checked});const n=this._cameraEnhancer.getSelectedCamera(),r=this._cameraEnhancer.getCapabilities();lo(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(r.torch?i(this,oa,"m",Pa).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):i(this,oa,"m",Pa).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),s(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(i(this,fa,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),i(this,oa,"m",ka).call(this,"Loading...",!1)}));const a=t.querySelectorAll(".camera-list div");return()=>e(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();s(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===s?()=>e(this,void 0,void 0,function*(){i(this,oa,"m",ka).call(this,"Accessing Camera...",!0);const t=lo(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&i(this,oa,"m",Pa).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&i(this,oa,"m",Pa).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),i(this,oa,"m",ka).call(this,"Loading...",!1)}):void 0},h=a();n.addEventListener("click",t=>e(this,void 0,void 0,function*(){t.stopPropagation(),h&&(yield h())}))}}})},Ta=function(e){const r=this._cameraView.getUIElement();r.shadowRoot.querySelector(".dce-sel-camera").remove(),r.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const s=e.querySelector(".barcode-scanner-container");s.style.display=oo()?"flex":"",this.config.scanMode===t.EnumScanMode.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(this.config.showResultView=!1);const o=this.config.showResultView;let a;if(this.config.container?(s.style.position="relative",a=this.config.container):a=document.body,"string"==typeof a&&(a=document.querySelector(a),null===a))throw new Error("Failed to get the container");let h=this.config.scannerViewConfig.container;if("string"==typeof h&&(h=document.querySelector(h),null===h))throw new Error("Failed to get the container of the scanner view.");let l=this.config.resultViewConfig.container;if("string"==typeof l&&(l=document.querySelector(l),null===l))throw new Error("Failed to get the container of the result view.");const c=e.querySelector(".scanner-view-container"),u=e.querySelector(".result-view-container"),d=e.querySelector(".loading-page");c.append(d),h&&(c.append(r),h.append(c)),l&&l.append(u),h||l?h&&!l?(this.config.container||(u.style.position="absolute"),l=u,a.append(u)):!h&&l&&(this.config.container||(c.style.position="absolute"),h=c,c.append(r),a.append(c)):(h=c,l=u,o&&(Object.assign(c.style,{width:oo()?"50%":"100%",height:oo()?"100%":"50%"}),Object.assign(u.style,{width:oo()?"50%":"100%",height:oo()?"100%":"50%"})),c.append(r),a.append(s)),document.querySelector(".result-view-container").style.display=o?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),n(this,la,()=>{Object.assign(s.style,{display:oo()?"flex":""}),!o||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(h.style,{width:oo()?"50%":"100%",height:oo()?"100%":"50%"}),Object.assign(l.style,{width:oo()?"50%":"100%",height:oo()?"100%":"50%"}))},"f"),window.addEventListener("resize",i(this,la,"f"))},Ia=function(t){t.querySelector(".resume").addEventListener("click",()=>e(this,void 0,void 0,function*(){document.querySelector(".features-group").style.display="flex",document.querySelector(".btn-close").style.display="block",document.querySelector(".resume").style.display="none",this._cameraView.getUIElement().shadowRoot.querySelector(".single-mode-mask").remove(),this._cameraView.getUIElement().shadowRoot.querySelectorAll(".single-barcode-result-option").forEach(t=>t.remove()),yield this._cameraEnhancer.resume(),yield new Promise(t=>{setTimeout(t,100)}),this._cvRouter.startCapturing(i(this,fa,"f"))}))},xa=function(){const n=new Ve;n.onCapturedResultReceived=n=>e(this,void 0,void 0,function*(){if(i(this,ga,"f")&&i(this,ga,"f").clearDrawingItems(),n.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of n.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));i(this,ga,"f").addDrawingItems(t)}this.config.scanMode===t.EnumScanMode.SM_SINGLE?i(this,oa,"m",Ra).call(this,n):i(this,oa,"m",Aa).call(this,n)}}),this._cvRouter.addResultReceiver(n)},Oa=function(){return e(this,void 0,void 0,function*(){i(this,ma,"f")||n(this,ma,new ta,"f"),i(this,ma,"f").enableResultCrossVerification(2,!0),i(this,ma,"f").enableResultDeduplication(2,!0),i(this,ma,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(i(this,ma,"f")),i(this,ma,"f").isResultCrossVerificationEnabled=()=>!1,i(this,ma,"f").isResultDeduplicationEnabled=()=>!1})},Ra=function(e){const n=this._cameraView.getUIElement().shadowRoot;let r=new Promise(t=>{if(e.decodedBarcodesResult.barcodeResultItems.length>1){i(this,oa,"m",Da).call(this);let r=[];for(let i of e.decodedBarcodesResult.barcodeResultItems){let e=0,n=0;for(let t=0;t<4;++t){let r=i.location.points[t];e+=r.x,n+=r.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:e/4,y:n/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px",transform:"translate(-50%, -50%)",animation:"1s infinite alternate result-option-flash","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{t(i)}),r.push(o)}n.append(...r)}else t(e.decodedBarcodesResult.barcodeResultItems[0])});r.then(n=>{const r=e.items.filter(t=>t.type===lt.CRIT_ORIGINAL_IMAGE)[0].imageData,s={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},originalImageResult:r,barcodeImage:(()=>{const t=U(r),e=n.location.points,i=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-i,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-i,e[0].y-s);for(let t=1;t`${t.formatString}_${t.text}`==`${e.formatString}_${e.text}`);-1===t?(e.count=1,i(this,ca,"f").barcodeResults.unshift(e),i(this,oa,"m",La).call(this,e)):(i(this,ca,"f").barcodeResults[t].count++,i(this,oa,"m",Ma).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(e)}},Da=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0",opacity:"0.5","background-color":"#4C4C4C"}),t.append(e),document.querySelector(".features-group").style.display="none",document.querySelector(".btn-close").style.display="none",document.querySelector(".resume").style.display="block",this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},La=function(e){if(!this.config.showResultView)return;const n=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==t.EnumScanMode.SM_SINGLE))return;const r=document.querySelector(".main-list");if(!e)return r.textContent="",void(this.config.showPoweredByDynamsoft&&(n.style.display=""));n.style.display="none";const s=(t=>{const e=i(this,da,"f").cloneNode(!0);e.querySelector(".format-string").innerText=t.formatString;e.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),e.id=`${t.formatString}_${t.text}`;return e.querySelector(".delete-icon").addEventListener("click",()=>{const e=[...document.querySelectorAll(".main-list .result-item")],n=e.findIndex(e=>e.id===`${t.formatString}_${t.text}`);i(this,ca,"f").barcodeResults.splice(n,1),e[n].remove(),0===i(this,ca,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),e})(e);r.insertBefore(s,document.querySelector(".result-item"))},Ma=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},Fa=function(n,r){r&&(n.style.display="",n.onchange=n=>e(this,void 0,void 0,function*(){const e=n.target.files,r={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success."},barcodeResults:[]};let s=0;i(this,oa,"m",ka).call(this,`Capturing... [${s}/${e.length}]`,!0);let o=!1;for(let t=0;t`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===e?(t.count=1,i(this,ca,"f").barcodeResults.unshift(t),i(this,oa,"m",La).call(this,t)):(i(this,ca,"f").barcodeResults[e].count++,i(this,oa,"m",Ma).call(this,e))}else if(o.decodedBarcodesResult.barcodeResultItems)for(let t of o.decodedBarcodesResult.barcodeResultItems){const e=r.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,r.barcodeResults.push(t))}i(this,oa,"m",ka).call(this,`Capturing... [${++s}/${e.length}]`,!0)}catch(e){r.status={code:t.EnumResultStatus.RS_FAILED,message:e.message||e},i(ja,aa,"f",ha).reject(new Error(r.status.message)),this.dispose()}i(this,oa,"m",ka).call(this,"Loading...",!1),this.config.scanMode===t.EnumScanMode.SM_SINGLE&&(i(ja,aa,"f",ha).resolve(r),this.dispose()),n.target.value=""}))},Pa=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},ka=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},Na=function(t){let e=At();Dt[e]=()=>{},Ot.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},ha={value:null};const Ua="undefined"==typeof self,Va="function"==typeof importScripts,Ga=(()=>{if(!Va){if(!Ua&&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"./"}})(),Wa=t=>{if(null==t&&(t="./"),Ua||Va);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Vt.engineResourcePaths.dbr={version:"11.2.20-dev-20251029130556",path:Ga,isInternal:!0},Bt.dbr={js:!1,wasm:!0,deps:[St.MN_DYNAMSOFT_LICENSE,St.MN_DYNAMSOFT_IMAGE_PROCESSING]},Nt.dbr={};const Ya="2.0.0";"string"!=typeof Vt.engineResourcePaths.std&&N(Vt.engineResourcePaths.std.version,Ya)<0&&(Vt.engineResourcePaths.std={version:Ya,path:Wa(Ga+`../../dynamsoft-capture-vision-std@${Ya}/dist/`),isInternal:!0});const Ha="3.0.10";(!Vt.engineResourcePaths.dip||"string"!=typeof Vt.engineResourcePaths.dip&&N(Vt.engineResourcePaths.dip.version,Ha)<0)&&(Vt.engineResourcePaths.dip={version:Ha,path:Wa(Ga+`../../dynamsoft-image-processing@${Ha}/dist/`),isInternal:!0});const Xa={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var za,qa,Ka,Za;!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"}(za||(za={})),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"}(qa||(qa={})),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_NEURAL_NETWORK=512]="LM_NEURAL_NETWORK",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(Ka||(Ka={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(Za||(Za={}));var Ja,$a,Qa=Object.freeze({__proto__:null,BarcodeReaderModule:class{static getVersion(){const t=kt.dbr&&kt.dbr.wasm;return`11.2.20-dev-20251029130556(Worker: ${kt.dbr&&kt.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}},EnumBarcodeFormat:Xa,get EnumDeblurMode(){return Za},get EnumExtendedBarcodeResultType(){return za},get EnumLocalizationMode(){return Ka},get EnumQRCodeErrorCorrectionLevel(){return qa}});function th(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:eh(e,t,"map"),t.getFieldRawValue=t=>eh(e,t,"raw"),t.getFieldMappingStatus=t=>ih(e,t),t.getFieldValidationStatus=t=>nh(e,t),delete t.fullCodeString}function eh(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=eh(r,e,i);if(void 0!==t)return t}}}function ih(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Ja[i.MappingStatus]):Ja.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=ih(n,e);if(void 0!==t)return t}}}function nh(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number($a[i.ValidationStatus]):$a.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=nh(n,e);if(void 0!==t)return t}}}function rh(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(Ja||(Ja={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}($a||($a={}));const sh=t=>t&&"object"==typeof t&&"function"==typeof t.then,oh=(async()=>{})().constructor;class ah extends oh{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,sh(t)?e=t:"function"==typeof t&&(e=new oh(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(sh(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class hh{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!Nt.license)throw Error("Module `license` is not existed.");await Nt.license.dynamsoft(),await Vt.loadWasm();const t=new hh,e=new ah;let i=At();return Dt[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},Ot.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){rh(this);let t=At();this.bDestroyed=!0,Dt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Ot.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(rh(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await k(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=At();Dt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Ot.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return rh(this),await new Promise((t,e)=>{let i=At();Dt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Ot.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(rh(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise((i,n)=>{let r=At();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(th(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Ot.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const lh="undefined"==typeof self,ch="function"==typeof importScripts,uh=(()=>{if(!ch){if(!lh&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();Vt.engineResourcePaths.dcp={version:"3.2.20-dev-20251029130614",path:uh,isInternal:!0},Bt.dcp={js:!0,wasm:!0,deps:[St.MN_DYNAMSOFT_LICENSE]},Nt.dcp={handleParsedResultItem:th};const dh="2.0.0";"string"!=typeof Vt.engineResourcePaths.std&&N(Vt.engineResourcePaths.std.version,dh)<0&&(Vt.engineResourcePaths.std={version:dh,path:(t=>{if(null==t&&(t="./"),lh||ch);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(uh+`../../dynamsoft-capture-vision-std@${dh}/dist/`),isInternal:!0}),Dt[-4]=async t=>{fh.onSpecLoadProgressChanged&&fh.onSpecLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class fh{static getVersion(){const t=kt.dcp&&kt.dcp.wasm;return`3.2.20-dev-20251029130614(Worker: ${kt.dcp&&kt.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await Vt.loadWasm(),await new Promise((i,n)=>{let r=At();Dt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],o=B(Vt.engineResourcePaths);Ot.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===Vt._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}}var gh=Object.freeze({__proto__:null,CodeParser:hh,CodeParserModule:fh,get EnumMappingStatus(){return Ja},get EnumValidationStatus(){return $a}});Vt._bundleEnv="DBR",Ue._defaultTemplate="ReadSingleBarcode",Vt.engineResourcePaths.dbrBundle={version:"11.2.2000",path:o,isInternal:!0},t.BarcodeScanner=ja,t.CVR=We,t.Core=Gt,t.DBR=Qa,t.DCE=ks,t.DCP=gh,t.License=so,t.Utility=Ba}); diff --git a/dist/dbr.bundle.mjs b/dist/dbr.bundle.mjs index 23800f6..fced737 100644 --- a/dist/dbr.bundle.mjs +++ b/dist/dbr.bundle.mjs @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 11.0.6000 +* @version 11.2.2000 * @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,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function e(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function i(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const n="undefined"==typeof self,r="function"==typeof importScripts,s=(()=>{if(!r){if(!n&&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"./"}})(),o=t=>{if(null==t&&(t="./"),n||r);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var a,h,l;!function(t){t[t.SM_SINGLE=0]="SM_SINGLE",t[t.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(a||(a={})),function(t){t[t.OM_NONE=0]="OM_NONE",t[t.OM_SPEED=1]="OM_SPEED",t[t.OM_COVERAGE=2]="OM_COVERAGE",t[t.OM_BALANCE=3]="OM_BALANCE",t[t.OM_DPM=4]="OM_DPM",t[t.OM_DENSE=5]="OM_DENSE"}(h||(h={})),function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(l||(l={}));const c=t=>t&&"object"==typeof t&&"function"==typeof t.then,u=(async()=>{})().constructor;let d=class extends u{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,c(t)?e=t:"function"==typeof t&&(e=new u(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(c(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function f(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function g(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var m,p,_;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(m||(m={})),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"}(p||(p={})),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"}(_||(_={}));const v="undefined"==typeof self,y="function"==typeof importScripts,w=(()=>{if(!y){if(!v&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),C=t=>{if(null==t&&(t="./"),v||y);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},E=t=>Object.prototype.toString.call(t),S=t=>Array.isArray?Array.isArray(t):"[object Array]"===E(t),b=t=>"number"==typeof t&&!Number.isNaN(t),T=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),I=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.radius)||t.radius<0||!b(t.startAngle)||!b(t.endAngle)),x=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),O=t=>!(!T(t)||!b(t.width)||t.width<=0||!b(t.height)||t.height<=0||!b(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!L(t.tag)),R=t=>!(!O(t)||!b(t.bytes.length)&&!b(t.bytes.ptr)),A=t=>!!O(t)&&t.bytes instanceof Uint8Array,D=t=>!(!T(t)||!b(t.left)||t.left<0||!b(t.top)||t.top<0||!b(t.right)||t.right<0||!b(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),L=t=>null===t||!!T(t)&&!!b(t.imageId)&&"type"in t,M=t=>!(!T(t)||!F(t.startPoint)||!F(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),F=t=>!!T(t)&&!!b(t.x)&&!!b(t.y),P=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),k=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!F(t)),N=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.width)||t.width<0||!b(t.height)||t.height<0),B=async(t,e)=>await new Promise((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}),j=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),U=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${q[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${q[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},G=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await H(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),W=t=>{A(t)&&(t=X(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},Y=(t,e)=>{A(e)&&(e=X(e));const i=W(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},H=async(t,e)=>{A(e)&&(e=X(e));const i=W(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},X=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===_.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===_.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},z=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),q={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var K,Z,J,$,Q,tt,et,it;let nt,rt,st,ot,at,ht=class t{get _isFetchingStarted(){return f(this,Q,"f")}constructor(){K.add(this),Z.set(this,[]),J.set(this,1),$.set(this,m.BOPM_BLOCK),Q.set(this,!1),tt.set(this,void 0),et.set(this,p.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!A(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(f(this,Z,"f").length>=f(this,J,"f"))switch(f(this,$,"f")){case m.BOPM_BLOCK:break;case m.BOPM_UPDATE:if(f(this,Z,"f").push(t),T(f(this,tt,"f"))&&b(f(this,tt,"f").imageId)&&1==f(this,tt,"f").keepInBuffer)for(;f(this,Z,"f").length>f(this,J,"f");){const t=f(this,Z,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==f(this,tt,"f").imageId});f(this,Z,"f").splice(t,1)}else f(this,Z,"f").splice(0,f(this,Z,"f").length-f(this,J,"f"))}else f(this,Z,"f").push(t)}getImage(){if(0===f(this,Z,"f").length)return null;let e;if(f(this,tt,"f")&&b(f(this,tt,"f").imageId)){const t=f(this,K,"m",it).call(this,f(this,tt,"f").imageId);if(t<0)throw new Error(`Image with id ${f(this,tt,"f").imageId} doesn't exist.`);e=f(this,Z,"f").slice(t,t+1)[0]}else e=f(this,Z,"f").pop();if([_.IPF_RGB_565,_.IPF_RGB_555,_.IPF_RGB_888,_.IPF_ARGB_8888,_.IPF_RGB_161616,_.IPF_ARGB_16161616,_.IPF_ABGR_8888,_.IPF_ABGR_16161616,_.IPF_BGR_888].includes(e.format)){if(f(this,et,"f")===p.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every(t=>b(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==E(e))throw new TypeError("Invalid 'keepInBuffer'.");g(this,tt,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){g(this,tt,null,"f")}hasImage(t){return f(this,K,"m",it).call(this,t)>=0}startFetching(){g(this,Q,!0,"f")}stopFetching(){g(this,Q,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(g(this,J,t,"f");f(this,Z,"f")&&f(this,Z,"f").length>t;)f(this,Z,"f").shift()}getMaxImageCount(){return f(this,J,"f")}getImageCount(){return f(this,Z,"f").length}clearBuffer(){f(this,Z,"f").length=0}isBufferEmpty(){return 0===f(this,Z,"f").length}setBufferOverflowProtectionMode(t){g(this,$,t,"f")}getBufferOverflowProtectionMode(){return f(this,$,"f")}setColourChannelUsageType(t){g(this,et,t,"f")}getColourChannelUsageType(){return f(this,et,"f")}};Z=new WeakMap,J=new WeakMap,$=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,K=new WeakSet,it=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return f(this,Z,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(nt=navigator,rt=nt.userAgent,st=nt.platform,ot=nt.mediaDevices),function(){if(!v){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:nt.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:st,search:"Win"},Mac:{str:st},Linux:{str:st}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||rt,o=r.search||e,a=r.verStr||rt,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||rt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=rt.indexOf("Windows NT")&&(r="HarmonyOS"),at={browser:i,version:n,OS:r}}v&&(at={browser:"ssr",version:0,OS:"ssr"})}();const lt="undefined"!=typeof WebAssembly&&rt&&!(/Safari/.test(rt)&&!/Chrome/.test(rt)&&/\(.+\s11_2_([2-6]).*\)/.test(rt)),ct=!("undefined"==typeof Worker),ut=!(!ot||!ot.getUserMedia),dt=async()=>{let t=!1;if(ut)try{(await ot.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var ft,gt,mt,pt,_t,vt,yt,wt,Ct;"Chrome"===at.browser&&at.version>66||"Safari"===at.browser&&at.version>13||"OPR"===at.browser&&at.version>43||"Edge"===at.browser&&at.version,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(ft||(ft={})),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"}(gt||(gt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(mt||(mt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV",t[t.GEM_END=-1]="GEM_END"}(pt||(pt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV",t[t.GTM_END=-1]="GTM_END"}(_t||(_t={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(vt||(vt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(yt||(yt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(wt||(wt={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(Ct||(Ct={}));const Et={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var St,bt,Tt,It,xt,Ot;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(St||(St={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(bt||(bt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(Tt||(Tt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(It||(It={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(xt||(xt={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(Ot||(Ot={}));const Rt={},At=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Rt[t]=Rt[t]||new d);await Promise.all(i)},Dt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=Rt[t]=Rt[t]||new d(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let Lt,Mt=0;const Ft=()=>Mt++,Pt={};let kt;const Nt=t=>{kt=t,Lt&&Lt.postMessage({type:"setBLog",body:{value:!!t}})};let Bt=!1;const jt=t=>{Bt=t,Lt&&Lt.postMessage({type:"setBDebug",body:{value:!!t}})},Ut={},Vt={},Gt={dip:{wasm:!0}},Wt={std:{version:"2.0.0",path:C(w+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.0.60-dev-20250812165815",path:w,isInternal:!0}};class Yt{static get engineResourcePaths(){return Wt}static set engineResourcePaths(t){Object.assign(Wt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return kt}static set _onLog(t){Nt(t)}static get _bDebug(){return Bt}static set _bDebug(t){jt(t)}static get _workerName(){return`${Yt._bundleEnv.toLowerCase()}.bundle.worker.js`}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Rt[t]&&Rt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=Rt.core;e=!i||i.isEmpty,e||await At("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),xt.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||xt.MN_DYNAMSOFT_CORE==t)return;let e=Gt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=Rt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await Dt(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await At(o);const i=V(Wt),r={};for(let e of t)r[e]=Gt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:Yt._bundleEnv,_useSimd:Yt._useSimd,_useMLBackend:Yt._useMLBackend};let a=new d;if(e){s.needLoadCore=!0;let t=i[`${Yt._bundleEnv.toLowerCase()}Bundle`]+Yt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),Lt=new Worker(t),Lt.onerror=t=>{let e=new Error(t.message);a.reject(e)},Lt.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":kt&&kt(e.message);break;case"task":try{Pt[n](r),delete Pt[n]}catch(t){throw delete Pt[n],t}break;case"event":try{Pt[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!kt,s.bd=Bt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await At("core");let h=Mt++;Pt[h]=t=>{if(t.success)Object.assign(Ut,t.versions),"{}"!==JSON.stringify(t.versions)&&(Yt._versions=t.versions),a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},Lt.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:lt,worker:ct,getUserMedia:ut,camera:await dt(),browser:at.browser,version:at.version,OS:at.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.0.60-dev-20250812165815(Worker: ${Ut.core&&Ut.core.worker||"Not Loaded"}, Wasm: ${Ut.core&&Ut.core.wasm||"Not Loaded"})`}static enableLogging(){ht._onLog=console.log,Yt._onLog=console.log}static disableLogging(){ht._onLog=null,Yt._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cfd",id:n,body:{count:t}})})}}Yt._bSupportDce4Module=-1,Yt._bSupportIRTModule=-1,Yt._versions=null,Yt._bundleEnv="DCV",Yt._useMLBackend=!1,Yt._useSimd=!0,Yt.browserInfo=at;var Ht={license:"",scanMode:a.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:Yt.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:s,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const Xt=t=>t&&"object"==typeof t&&"function"==typeof t.then,zt=(async()=>{})().constructor;class qt extends zt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xt(t)?e=t:"function"==typeof t&&(e=new zt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Xt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Kt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Zt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Jt=t=>t&&"object"==typeof t&&"function"==typeof t.then,$t=(async()=>{})().constructor;let Qt=class extends $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,Jt(t)?e=t:"function"==typeof t&&(e=new $t(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Jt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},te=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var ee={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1,onProcessedDocumentResultReceived:!1};const ie=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};let ne=class{constructor(t){this._irrRegistryState=ee,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ie(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach((t,e)=>{i[e]=t}),t._observedTaskMap.clear()}return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ie(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const re="undefined"==typeof self,se="function"==typeof importScripts,oe=(()=>{if(!se){if(!re&&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"./"}})(),ae=t=>{if(null==t&&(t="./"),re||se);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var he;Yt.engineResourcePaths.cvr={version:"3.0.60-dev-20250812165839",path:oe,isInternal:!0},Gt.cvr={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING,xt.MN_DYNAMSOFT_NEURAL_NETWORK]},Gt.dnn={wasm:!0,deps:[xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.cvr={};const le="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,le)<0&&(Yt.engineResourcePaths.std={version:le,path:ae(oe+`../../dynamsoft-capture-vision-std@${le}/dist/`),isInternal:!0});const ce="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,ce)<0)&&(Yt.engineResourcePaths.dip={version:ce,path:ae(oe+`../../dynamsoft-image-processing@${ce}/dist/`),isInternal:!0});const ue="2.0.10";(!Yt.engineResourcePaths.dnn||"string"!=typeof Yt.engineResourcePaths.dnn&&U(Yt.engineResourcePaths.dnn.version,ue)<0)&&(Yt.engineResourcePaths.dnn={version:ue,path:ae(oe+`../../dynamsoft-capture-vision-dnn@${ue}/dist/`),isInternal:!0});let de=class{static getVersion(){return this._version}};var fe,ge,me,pe,_e,ve,ye,we,Ce,Ee,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le,Me,Fe,Pe,ke;function Ne(t,e){if(t&&t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Ne(t.referencedItem,e)}}function Be(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function je(t){let e=!1;const i=[mt.EC_UNSUPPORTED_JSON_KEY_WARNING,mt.EC_LICENSE_AUTH_QUOTA_EXCEEDED,mt.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}de._version=`3.0.60-dev-20250812165839(Worker: ${null===(he=Ut.cvr)||void 0===he?void 0:he.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(fe||(fe={}));const Ue={onTaskResultsReceived:()=>{},isFilter:!0};Pt[-2]=async t=>{Ve.onDataLoadProgressChanged&&Ve.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let Ve=class t{constructor(){ge.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(Yt.browserInfo.OS)?2048:4096,this.onCaptureError=null,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._dynamsoft=!0,me.set(this,null),pe.set(this,null),_e.set(this,null),ve.set(this,null),ye.set(this,null),we.set(this,new Set),Ce.set(this,new Set),Ee.set(this,new Set),Se.set(this,500),be.set(this,0),Te.set(this,0),Ie.set(this,!1),xe.set(this,!1),Oe.set(this,!1),Re.set(this,null),Ae.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Kt(this,Oe,"f")}static async createInstance(e=!0){if(!Vt.license)throw Error("The `license` module cannot be found.");await Vt.license.dynamsoft(),await Yt.loadWasm();const i=new t,n=new Qt;let r=Ft();return Pt[r]=async t=>{t.success?(i._instanceID=t.instanceID,i._currentSettings=JSON.parse(JSON.parse(t.outputSettings).data),de._version=`3.0.60-dev-20250812165839(Worker: ${Ut.cvr.worker}, Wasm: ${t.version})`,Zt(i,xe,!0,"f"),Zt(i,ve,i.getIntermediateResultManager(),"f"),Zt(i,xe,!1,"f"),n.resolve(i)):je({message:t.message,rj:n.reject,stack:t.stack,functionName:"createInstance"})},Lt.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendModelBuffer(t,e){return await Yt.loadWasm(),await new Promise((i,n)=>{let r=Ft();const s=V(Yt.engineResourcePaths);let o;Pt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&je({message:e.errorString?e.errorString:"Append Model Buffer Failed.",rj:n,errorCode:e.errorCode,functionName:"appendModelBuffer"}),i(e)}je({message:t.message,rj:n,stack:t.stack,functionName:"appendModelBuffer"})},e?o=e:"DCV"===Yt._bundleEnv?o=s.dcvData+"models/":"DBR"===Yt._bundleEnv&&(o=s.dbrBundle+"models/"),Lt.postMessage({type:"cvr_appendModelBuffer",id:r,body:{modelName:t,path:o}})})}async _singleFrameModeCallback(t){for(let e of Kt(this,we,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;for(let t of Kt(this,we,"f"))t.isDce?t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}):Kt(this,ge,"m",Le).call(this,t,i)}setInput(t){if(Be(this),!t)return Kt(this,Re,"f")&&(Kt(this,ve,"f").removeResultReceiver(Kt(this,Re,"f")),Zt(this,Re,null,"f")),Kt(this,Ae,"f")&&(Kt(this,we,"f").delete(Kt(this,Ae,"f")),Zt(this,Ae,null,"f")),void Zt(this,me,null,"f");if(Zt(this,me,t,"f"),t.isCameraEnhancer){Kt(this,ve,"f")&&(Kt(this,me,"f")._intermediateResultReceiver.isDce=!0,Kt(this,ve,"f").addResultReceiver(Kt(this,me,"f")._intermediateResultReceiver),Zt(this,Re,Kt(this,me,"f")._intermediateResultReceiver,"f"));const t=Kt(this,me,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Kt(this,we,"f").add(e),Zt(this,Ae,e,"f")}}}getInput(){return Kt(this,me,"f")}addImageSourceStateListener(t){if(Be(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Kt(this,Ce,"f").add(t)}removeImageSourceStateListener(t){return Be(this),Kt(this,Ce,"f").delete(t)}addResultReceiver(t){if(Be(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Kt(this,we,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Be(this),Kt(this,we,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Kt(this,we,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new Qt;let i=Ft();return Pt[i]=async t=>{t.success?e.resolve():je({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},Lt.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Be(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Kt(this,Ee,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Be(this),Kt(this,Ee,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Kt(this,ve,"f").removeResultReceiver(Ue),0===Kt(this,Ee,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},e={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1};return await Kt(this,ge,"m",Me).call(this,t),void await Kt(this,ge,"m",Fe).call(this,e)}for(let t of Kt(this,Ee,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(ft.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(ft.CRIT_BARCODE)&&([...Kt(this,ve,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Kt(this,ve,"f").addResultReceiver(Ue)),await Kt(this,ge,"m",Me).call(this,t.verificationEnabled),await Kt(this,ge,"m",Fe).call(this,t.duplicateFilterEnabled),await Kt(this,ge,"m",Pe).call(this,t.duplicateForgetTime)}async startCapturing(e){if(Be(this),!this._isPauseScan)return;if(!Kt(this,me,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);const i=await this.containsTask(e);for(let t of Kt(this,Ee,"f"))await this.addResultFilter(t);const n=V(Yt.engineResourcePaths);return Kt(this,me,"f").isCameraEnhancer&&(i.includes("ddn")?Kt(this,me,"f").setPixelFormat(_.IPF_ABGR_8888):Kt(this,me,"f").setPixelFormat(_.IPF_GRAYSCALED)),void 0!==Kt(this,me,"f").singleFrameMode&&"disabled"!==Kt(this,me,"f").singleFrameMode?(this._templateName=e,void Kt(this,me,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):(Kt(this,me,"f").getColourChannelUsageType()===p.CCUT_AUTO&&Kt(this,me,"f").setColourChannelUsageType(i.includes("ddn")?p.CCUT_FULL_CHANNEL:p.CCUT_Y_CHANNEL_ONLY),Kt(this,_e,"f")&&Kt(this,_e,"f").isPending?Kt(this,_e,"f"):(Zt(this,_e,new Qt((t,i)=>{if(this.disposed)return;let r=Ft();Pt[r]=async n=>{Kt(this,_e,"f")&&!Kt(this,_e,"f").isFulfilled&&(n.success?(this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Kt(this,me,"f").startFetching(),this._loopReadVideo(e),t()},0)):je({message:n.message,rj:i,stack:n.stack,functionName:"startCapturing"}))},Lt.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:n}})}),"f"),await Kt(this,_e,"f")))}stopCapturing(){Be(this),Kt(this,me,"f")&&(Kt(this,me,"f").isCameraEnhancer&&void 0!==Kt(this,me,"f").singleFrameMode&&"disabled"!==Kt(this,me,"f").singleFrameMode?Kt(this,me,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Kt(this,ge,"m",ke).call(this),Kt(this,me,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Zt(this,_e,null,"f"),Kt(this,me,"f").setColourChannelUsageType(p.CCUT_AUTO)))}async containsTask(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));je({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},Lt.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Zt(this,Ie,!0,"f"),Kt(this,me,"f").isBufferEmpty())if(Kt(this,me,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(fe.ISS_BUFFER_EMPTY);else if(!Kt(this,me,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(fe.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Kt(this,me,"f").isBufferEmpty()&&Kt(this,me,"f").isCameraEnhancer)try{Kt(this,me,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Kt(this,me,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Kt(this,me,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Kt(this,me,"f").isCameraEnhancer&&Kt(this,me,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Kt(this,me,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Kt(this,we,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;for(let e of Kt(this,we,"f"))if(e.isDce){const i=Date.now();if(e.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),t._onLog){const e=Date.now()-i;e>10&&t._onLog(`draw result time: ${e}`)}}else{for(let t of Kt(this,Ee,"f"))t.onDecodedBarcodesReceived(n),t.onRecognizedTextLinesReceived(n),t.onProcessedDocumentResultReceived(n);Kt(this,ge,"m",Le).call(this,e,n)}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Kt(this,me,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Kt(this,me,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async capture(e,i){let n;if(Be(this),i||(i=t._defaultTemplate),Zt(this,Ie,!1,"f"),A(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await B(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Zt(this,Te,this.maxImageSideLength/o,"f"),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,pe,"f")||Zt(this,pe,document.createElement("canvas"),"f");const a=Kt(this,pe,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Zt(this,Te,this.maxImageSideLength/o,"f"),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,pe,"f")||Zt(this,pe,document.createElement("canvas"),"f");const a=Kt(this,pe,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Ft();V(Yt.engineResourcePaths);const l=new Qt;return Pt[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;t.hasOwnProperty("_needContinueProcess")&&delete t._needContinueProcess,e.bytes=i.bytes;for(let i of t.items)0!==Kt(this,Te,"f")&&Ne(i,Kt(this,Te,"f")),i.type===ft.CRIT_ORIGINAL_IMAGE?i.imageData=e:[ft.CRIT_DESKEWED_IMAGE,ft.CRIT_ENHANCED_IMAGE].includes(i.type)?Vt.ddn&&Vt.ddn.handleDeskewedAndEnhancedImageResultItem(i):i.type===ft.CRIT_PARSED_RESULT&&Vt.dcp&&Vt.dcp.handleParsedResultItem(i);const n=t.processedDocumentResult;if(n){if(n.deskewedImageResultItems)for(let t=0;tKt(this,Se,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),Zt(this,be,s,"f")),Zt(this,Te,0,"f"),l.resolve(t)}catch(i){je({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else je({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),Lt.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Kt(this,Ie,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(Be(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await B(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Ft();Pt[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&je({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}je({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},Lt.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return Be(this),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&je({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}je({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},Lt.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,null,2,function(t,e){return e instanceof Array?JSON.stringify(e):e},2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return Be(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&je({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}je({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},Lt.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return Be(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&je({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}je({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},Lt.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return Be(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&je({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}je({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},Lt.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return Be(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&je({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}je({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},Lt.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return Kt(this,ye,"f")||Zt(this,ye,new te(this),"f"),Kt(this,ye,"f")}getIntermediateResultManager(){if(Be(this),!Kt(this,xe,"f")&&0!==Yt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Kt(this,ve,"f")||Zt(this,ve,new ne(this),"f"),Kt(this,ve,"f")}async parseRequiredResources(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));je({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},Lt.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){Be(this),Kt(this,_e,"f")&&this.stopCapturing(),Zt(this,me,null,"f"),Kt(this,we,"f").clear(),Kt(this,Ce,"f").clear(),Kt(this,Ee,"f").clear(),Kt(this,ve,"f")._intermediateResultReceiverSet.clear(),Zt(this,Oe,!0,"f");let t=Ft();Pt[t]=t=>{t.success||je({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},Lt.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Kt(this,me,"f"),promiseStartScan:Kt(this,_e,"f"),intermediateResultManager:Kt(this,ve,"f"),bufferdItemsManager:Kt(this,ye,"f"),resultReceiverSet:Kt(this,we,"f"),isaStateListenerSet:Kt(this,Ce,"f"),resultFilterSet:Kt(this,Ee,"f"),compressRate:Kt(this,Te,"f"),canvas:Kt(this,pe,"f"),isScanner:Kt(this,Ie,"f"),innerUseTag:Kt(this,xe,"f"),isDestroyed:Kt(this,Oe,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}je({message:i.message,rj:e,stack:i.stack,functionName:""})},Lt.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};me=new WeakMap,pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Re=new WeakMap,Ae=new WeakMap,ge=new WeakSet,De=function(t,e){const i=t.intermediateResult;if(i){let t=0;for(let n of Kt(this,ve,"f")._intermediateResultReceiverSet){t++;for(let r of i){if(["onTaskResultsReceived","onTargetROIResultsReceived"].includes(r.info.callbackName)){for(let t of r.intermediateResultUnits)t.originalImageTag=e.tag?e.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);t===Kt(this,ve,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}t&&t.hasOwnProperty("intermediateResult")&&delete t.intermediateResult},Le=function(t,e){e.decodedBarcodesResult&&t.onDecodedBarcodesReceived&&t.onDecodedBarcodesReceived(e.decodedBarcodesResult),e.recognizedTextLinesResult&&t.onRecognizedTextLinesReceived&&t.onRecognizedTextLinesReceived(e.recognizedTextLinesResult),e.processedDocumentResult&&t.onProcessedDocumentResultReceived&&t.onProcessedDocumentResultReceived(e.processedDocumentResult),e.parsedResult&&t.onParsedResultsReceived&&t.onParsedResultsReceived(e.parsedResult),t.onCapturedResultReceived&&t.onCapturedResultReceived(e)},Me=async function(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);je({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Fe=async function(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);je({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},Pe=async function(t){return Be(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);je({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},ke=async function(){let t=Ft();const e=new Qt;return Pt[t]=async t=>{if(t.success)return e.resolve();je({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},Lt.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},Ve._defaultTemplate="Default";let Ge=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},We=class{constructor(){this._observedResultUnitTypes=Et.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}};var Ye;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadSingleBarcode",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Ye||(Ye={}));const He="undefined"==typeof self,Xe="function"==typeof importScripts,ze=(()=>{if(!Xe){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"./"}})();Yt.engineResourcePaths.dce={version:"4.2.3-dev-20250812165927",path:ze,isInternal:!0},Gt.dce={wasm:!1,js:!1},Vt.dce={};let qe,Ke,Ze,Je,$e,Qe=class{static getVersion(){return"4.2.3-dev-20250812165927"}};function ti(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ei(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(qe=navigator,Ke=qe.userAgent,Ze=qe.platform,Je=qe.mediaDevices),function(){if(!He){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:qe.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:Ze,search:"Win"},Mac:{str:Ze},Linux:{str:Ze}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Ke,o=r.search||e,a=r.verStr||Ke,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Ke,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Ke.indexOf("Windows NT")&&(r="HarmonyOS"),$e={browser:i,version:n,OS:r}}He&&($e={browser:"ssr",version:0,OS:"ssr"})}();const ii="undefined"!=typeof WebAssembly&&Ke&&!(/Safari/.test(Ke)&&!/Chrome/.test(Ke)&&/\(.+\s11_2_([2-6]).*\)/.test(Ke)),ni=!("undefined"==typeof Worker),ri=!(!Je||!Je.getUserMedia),si=async()=>{let t=!1;if(ri)try{(await Je.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===$e.browser&&$e.version>66||"Safari"===$e.browser&&$e.version>13||"OPR"===$e.browser&&$e.version>43||"Edge"===$e.browser&&$e.version;var oi={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some(function(e){return"function"==typeof e.contains&&e.contains(t,!0)})},complexity:function(){return this._objects.reduce(function(t,e){return t+(e.complexity?e.complexity():0)},0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach(function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))}),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,I=-E*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kE)for(var T=1,I=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,R=E.length,A=R;R--;)I=(O=1-(f=E[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(function(t){for(var i=t.slice(0),n={},r=1;r=e})}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach(function(t){t.cancel()}),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter(function(e){return"object"==typeof e.target&&e.target.canvas===t});return e.forEach(function(t){t.cancel()}),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach(function(t){t.cancel()}),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find(function(e){return e.cancel===t})},findAnimationsByTarget:function(t){return t?this.filter(function(e){return e.target===t}):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map(function(t,e){return v[e]-_[e]}):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map(function(t,e){return m(n,_[e],y[e],c)}):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!o){if(!f(w,C,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",S=0,b=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=C.width-r*c,b=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y(function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach(function(e){i[e]=t[e]}),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach(function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s})}(0,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,function(t,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(e){this[e]!==i[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)},this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find(function(e){return!0===t[e]}):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach(function(i){e[i]=t[i]}),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach(function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})}),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter(function(e){return!e.onSelect({e:t})})),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){r.clear(),r._setBgOverlay(n,function(){s?r._enlivenObjects([s],function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)}):r.__setupCanvas.call(r,n,t,o,e)})},i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach(function(t,e){r.insertAt(t,e)}),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],function(e){r[t]=e[0],i[t]=!0,n&&n()}):this["set"+b.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},null,i):e&&e([])},_toDataURL:function(t,e){this.clone(function(i){e(i.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,i){this.clone(function(n){i(n.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(i,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,function(){i.renderAll(),t&&t(i)}),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach(function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])}),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var o=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,function(){var t=s?new o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,o=b.util.sin(n)*r;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach(function(t){r[t]=e[t]}),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl(function(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,function(t){delete t.points,i&&i(t)},"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r}),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter(function(t){return t&&!t.isNeutralState()}),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,function(){var n=new b.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,function(t,n){e&&e(new b.Image(t,i),n)},null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach(function(t){t.applyTo(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(b-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},ai={};function hi(t){var e=ai[t];if(void 0!==e)return e.exports;var i=ai[t]={exports:{}};return oi[t](i,i.exports,hi),i.exports}hi.d=(t,e)=>{for(var i in e)hi.o(e,i)&&!hi.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},hi.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var li={};(()=>{let t;hi.d(li,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?hi(653).fabric:{version:"5.2.1"}})();var ci,ui,di,fi,gi=li.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"}(ci||(ci={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(ui||(ui={})),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"}(di||(di={})),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"}(fi||(fi={}));const mi=t=>"number"==typeof t&&!Number.isNaN(t),pi=t=>"string"==typeof t;var _i,vi,yi,wi,Ci,Ei,Si,bi,Ti,Ii,xi;!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"}(Ci||(Ci={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(Ei||(Ei={}));let Oi=class{get mediaType(){return new Map([["rect",ci.DIMT_RECTANGLE],["quad",ci.DIMT_QUADRILATERAL],["text",ci.DIMT_TEXT],["arc",ci.DIMT_ARC],["image",ci.DIMT_IMAGE],["polygon",ci.DIMT_POLYGON],["line",ci.DIMT_LINE],["group",ci.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(ti(this,vi,"f")){case ui.DIS_DEFAULT:return"default";case ui.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"===ti(this,yi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===ti(this,yi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),ei(this,yi,t,"f")}get coordinateBase(){return ti(this,yi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(_i.add(this),vi.set(this,void 0),yi.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&&!mi(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(ui.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(ui.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(ui.DIS_SELECTED):this.setState(ui.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){ei(this,vi,t,"f")}getState(){return ti(this,vi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Li),actionName:"modifyPolygon",pointIndex:i}),t},{}),ei(this,bi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map(t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2})),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce(function(t,e,n){return t["p"+n]=new gi.Control({positionHandler:Ai,actionHandler:Mi(n>0?n-1:i,Li),actionName:"modifyPolygon",pointIndex:n}),t},{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=gi.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){ti(this,bi,"f")&&this.setPolygon(ti(this,bi,"f"))}setPolygon(t){if(!P(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 ei(this,bi,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 ti(this,bi,"f")?JSON.parse(JSON.stringify(ti(this,bi,"f"))):null}};bi=new WeakMap;let Pi=class extends Oi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return ti(this,Ii,"f")}constructor(t,e,i,n){if(super(null,n),Ti.set(this,void 0),Ii.set(this,void 0),!N(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new gi.Image(t,{left:e.x,top:e.y}));else{if(!A(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===_.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map(t=>t.split("\t")))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2})),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new gi.Control({positionHandler:Ai,actionHandler:Mi(i>0?i-1:n,Li),actionName:"modifyPolygon",pointIndex:i}),t},{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=gi.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){ti(this,Bi,"f")&&this.setLine(ti(this,Bi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!M(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 ei(this,Bi,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 ti(this,Bi,"f")?JSON.parse(JSON.stringify(ti(this,Bi,"f"))):null}}Bi=new WeakMap;let Vi=class extends Fi{constructor(t,e){if(super({points:null==t?void 0:t.points},e),ji.set(this,void 0),!k(t))throw new TypeError("Invalid 'quad'.");ei(this,ji,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){ti(this,ji,"f")&&this.setQuad(ti(this,ji,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!k(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 ei(this,ji,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 ti(this,ji,"f")?JSON.parse(JSON.stringify(ti(this,ji,"f"))):null}};ji=new WeakMap;class Gi extends Oi{constructor(t){super(new gi.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(ui.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(ui.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("deselected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map(t=>t.getDrawingItem())}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const Wi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Yi=t=>!!pi(t)&&""!==t,Hi=t=>!(!Wi(t)||"id"in t&&!mi(t.id)||"lineWidth"in t&&!mi(t.lineWidth)||"fillStyle"in t&&!Yi(t.fillStyle)||"strokeStyle"in t&&!Yi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Yi(t.fontFamily)||"fontSize"in t&&!mi(t.fontSize));class Xi{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(N(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!D(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var zi,qi;class Ki{constructor(){zi.set(this,new Map),qi.set(this,!1)}get disposed(){return ti(this,qi,"f")}on(t,e){t=t.toLowerCase();const i=ti(this,zi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else ti(this,zi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=ti(this,zi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=ti(this,zi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=ti(this,zi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){ei(this,qi,!0,"f")}}function Zi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Ji(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function $i(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}zi=new WeakMap,qi=new WeakMap;const Qi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};class tn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*r[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return tn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return tn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return tn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var en,nn,rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,br,Tr,Ir,xr,Or;class Rr{static createDrawingStyle(t){if(!Hi(t))throw new Error("Invalid style definition.");let e,i=Rr.USER_START_STYLE_ID;for(;ti(Rr,en,"f",nn).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in ti(Rr,en,"f",rn))n.hasOwnProperty(t)||(n[t]=ti(Rr,en,"f",rn)[t]);return ti(Rr,en,"f",nn).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=ti(Rr,en,"f",nn).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(ti(Rr,en,"f",nn).values())))}static _updateDrawingStyle(t,e){if(!Hi(e))throw new Error("Invalid style definition.");const i=ti(Rr,en,"f",nn).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}en=Rr,Rr.STYLE_BLUE_STROKE=1,Rr.STYLE_GREEN_STROKE=2,Rr.STYLE_ORANGE_STROKE=3,Rr.STYLE_YELLOW_STROKE=4,Rr.STYLE_BLUE_STROKE_FILL=5,Rr.STYLE_GREEN_STROKE_FILL=6,Rr.STYLE_ORANGE_STROKE_FILL=7,Rr.STYLE_YELLOW_STROKE_FILL=8,Rr.STYLE_BLUE_STROKE_TRANSPARENT=9,Rr.STYLE_GREEN_STROKE_TRANSPARENT=10,Rr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Rr.USER_START_STYLE_ID=1024,nn={value:new Map([[Rr.STYLE_BLUE_STROKE,{id:Rr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_GREEN_STROKE,{id:Rr.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}],[Rr.STYLE_ORANGE_STROKE,{id:Rr.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}],[Rr.STYLE_YELLOW_STROKE,{id:Rr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_BLUE_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_GREEN_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_ORANGE_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_YELLOW_STROKE_FILL,{id:Rr.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}],[Rr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Rr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Rr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Rr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Rr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},rn={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&&(gi.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(gi.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),gi.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},gi.Object.prototype.transparentCorners=!1,gi.Object.prototype.cornerSize=20,gi.Object.prototype.touchCornerSize=100,gi.Object.prototype.cornerColor="rgb(254,142,20)",gi.Object.prototype.cornerStyle="circle",gi.Object.prototype.strokeUniform=!0,gi.Object.prototype.hasBorders=!1,gi.Canvas.prototype.containerClass="",gi.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=gi.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},gi.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;ii&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Ar{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 gi.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])},0)}}),e.on("before:selection:cleared",function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.fabricCanvas.id=e,this.id=e,e){case Ar.DDN_LAYER_ID:n=Rr.getDrawingStyle(Rr.STYLE_BLUE_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_BLUE_STROKE_FILL);break;case Ar.DBR_LAYER_ID:n=Rr.getDrawingStyle(Rr.STYLE_ORANGE_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_ORANGE_STROKE_FILL);break;case Ar.DLR_LAYER_ID:n=Rr.getDrawingStyle(Rr.STYLE_GREEN_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_GREEN_STROKE_FILL);break;default:n=Rr.getDrawingStyle(Rr.STYLE_YELLOW_STROKE),r=Rr.getDrawingStyle(Rr.STYLE_YELLOW_STROKE_FILL)}for(let t of Oi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Rr.getDrawingStyle(t.styleId);return Rr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems(e=>e._mediaType===t);for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Rr.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Rr.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Rr.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Oi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Oi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Rr.getDrawingStyle(t.styleId);else{s=Rr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Oi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Rr.getDrawingStyle(t.styleId);else{s=Rr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Rr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase()):e=Oi.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Oi.arrStyleSelectors;const n=Rr.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ci.DIMT_RECTANGLE&&n.push("rect"),i&ci.DIMT_QUADRILATERAL&&n.push("quad"),i&ci.DIMT_TEXT&&n.push("text"),i&ci.DIMT_ARC&&n.push("arc"),i&ci.DIMT_IMAGE&&n.push("image"),i&ci.DIMT_POLYGON&&n.push("polygon"),i&ci.DIMT_LINE&&n.push("line");const r=[];e&ui.DIS_DEFAULT&&r.push("default"),e&ui.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Ar.DDN_LAYER_ID=1,Ar.DBR_LAYER_ID=2,Ar.DLR_LAYER_ID=3,Ar.USER_DEFINED_LAYER_BASE_ID=100,Ar.TIP_LAYER_ID=999;class Dr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Ar(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 Lr extends Ni{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),sn.set(this,void 0),on.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&ei(this,on,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},ti(this,sn,"f")),"f")}getDuration(){return ti(this,sn,"f")}}sn=new WeakMap,on=new WeakMap;class Mr{constructor(){an.add(this),hn.set(this,void 0),ln.set(this,void 0),cn.set(this,void 0),un.set(this,!0),this._drawingLayerManager=new Dr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Ar.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Ar.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()!==Ar.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(!(Wi(e=t)&&F(e.topLeftPoint)&&mi(e.width))||e.width<=0||!mi(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;ei(this,hn,JSON.parse(JSON.stringify(t)),"f"),ti(this,hn,"f").coordinateBase||(ti(this,hn,"f").coordinateBase="view"),ei(this,cn,t.duration,"f"),ti(this,an,"m",mn).call(this)}getTipConfig(){return ti(this,hn,"f")?ti(this,hn,"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()),ei(this,un,t,"f")}isTipVisible(){return ti(this,un,"f")}updateTipMessage(t){if(!ti(this,hn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Rr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Ar.TIP_LAYER_ID)||this._createDrawingLayer(Ar.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=ti(this,an,"m",dn).call(this,t,ti(this,hn,"f").topLeftPoint.x,ti(this,hn,"f").topLeftPoint.y,ti(this,hn,"f").width,ti(this,hn,"f").coordinateBase,this._tipStyleId),ti(this,an,"m",fn).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",ti(this,un,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),ti(this,ln,"f")&&clearTimeout(ti(this,ln,"f")),ti(this,cn,"f")>=0&&ei(this,ln,setTimeout(()=>{ti(this,an,"m",gn).call(this)},ti(this,cn,"f")),"f")}}hn=new WeakMap,ln=new WeakMap,cn=new WeakMap,un=new WeakMap,an=new WeakSet,dn=function(t,e,i,n,r,s){const o=new Lr(t,e,i,n,s);return o.coordinateBase=r,o},fn=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},gn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},mn=function(){if(!this._tip)return;const t=ti(this,hn,"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 Fr extends HTMLElement{constructor(){super(),pn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),ei(this,pn,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return ti(this,pn,"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())}}pn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Fr);class Pr extends Mr{static get engineResourcePath(){const t=V(Yt.engineResourcePaths);return"DCV"===Yt._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Pr._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Pr._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Pr.engineResourcePath)}static async createInstance(t){const e=new Pr;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Pr.engineResourcePath)),await e.setUIElement(t||Pr.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==ti(this,In,"f")){if(ei(this,In,t,"f"),ti(this,_n,"m",Rn).call(this))ei(this,Cn,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"),!ti(this,Cn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes($e.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ei(this,Cn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}ti(this,_n,"m",Rn).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 ti(this,In,"f")}get disposed(){return ti(this,On,"f")}constructor(){super(),_n.add(this),vn.set(this,void 0),yn.set(this,void 0),wn.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",Cn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._poweredBy=null,En.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Sn.set(this,!1),bn.set(this,!1),Tn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{ti(this,_n,"m",Fn).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()&&ti(this,_n,"m",Mn).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Pr._onLog&&Pr._onLog("window resize event triggered."),ti(this,Tn,"f").width===document.documentElement.clientWidth&&ti(this,Tn,"f").height===document.documentElement.clientHeight||(ti(this,Tn,"f").width=document.documentElement.clientWidth,ti(this,Tn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},In.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!ti(this,_n,"m",Rn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout(()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)},0)}),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},xn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{e.forEach(t=>Pr._transformCoordinates(t,i,n,r,s,o,a));const c=new Vi({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]),ti(this,xn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case ft.CRIT_ORIGINAL_IMAGE:break;case ft.CRIT_BARCODE:m=this.getDrawingLayer(Ar.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,Rr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_TEXT_LINE:m=this.getDrawingLayer(Ar.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,Rr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Ar.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Rr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case ft.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(Ar.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Rr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case ft.CRIT_PARSED_RESULT:case ft.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}if(t.decodedBarcodesResult)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f));if(t.recognizedTextLinesResult)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult){if(t.processedDocumentResult.detectedQuadResultItems)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f));if(t.processedDocumentResult.deskewedImageResultItems)for(let e=0;ePr._transformCoordinates(t,h,l,c,u,d,f))}}},On.set(this,!1),this.eventHandler=new Ki,this.eventHandler.on("content:updated",()=>{ti(this,vn,"f")&&clearTimeout(ti(this,vn,"f")),ei(this,vn,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",()=>{ti(this,yn,"f")&&clearTimeout(ti(this,yn,"f")),ei(this,yn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),ti(this,_n,"m",Rn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes($e.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ei(this,Cn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||ti(this,_n,"m",Rn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||ti(this,_n,"m",Rn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||ti(this,_n,"m",Fn).call(this),ti(this,_n,"m",Rn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),ti(this,_n,"m",Rn).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;Pr._onLog&&Pr._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()}));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}ti(this,Tn,"f").width=document.documentElement.clientWidth,ti(this,Tn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;ti(this,_n,"m",Rn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),ti(this,_n,"m",Fn).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,ei(this,Cn,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return ti(this,Cn,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!ti(this,Cn,"f"))return;if(ti(this,Cn,"f").style.objectFit=t,ti(this,_n,"m",Rn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();ti(this,_n,"m",Pn).call(this,e,i),ti(this,_n,"m",An).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(ti(this,_n,"m",Rn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=ti(this,Cn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=ti(this,Cn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){D(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):N(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=Xi.convert(this.scanRegion,t.width,t.height,this);ei(this,En,e,"f"),ti(this,wn,"f")&&clearTimeout(ti(this,wn,"f")),ei(this,wn,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}ti(this,_n,"m",An).call(this,t,e),ti(this,_n,"m",Pn).call(this,t,e)},0),"f")}getConvertedRegion(){return ti(this,En,"f")}setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=ti(this,Cn,"f").videoWidth,i=ti(this,Cn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=ti(this,Cn,"f").videoWidth,e=ti(this,Cn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove()),ti(this,xn,"f").length=0}dispose(){this._unbindUI(),ei(this,On,!0,"f")}}vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Sn=new WeakMap,bn=new WeakMap,Tn=new WeakMap,In=new WeakMap,xn=new WeakMap,On=new WeakMap,_n=new WeakSet,Rn=function(){return"disabled"!==this._singleFrameMode},An=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)},Dn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Ln=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Mn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Fn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Pn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach(e=>t.attachShader(i,e)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);ei(this,Bn,{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"),ei(this,jn,e(t),"f"),ei(this,Nn,i(t),"f"),ei(this,kn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,o,m)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[fi.GREY,fi.GREY32].includes(p)?1:0);let _,v,y=tn.translate(tn.identity(),-1,-1);y=tn.scale(y,2,2),y=tn.scale(y,1/t.canvas.width,1/t.canvas.height),_=tn.translate(y,u,d),_=tn.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=tn.translate(tn.identity(),1,0),v=tn.scale(v,-1,1),v=tn.translate(v,a/i,h/n),v=tn.scale(v,l/i,c/n)):(v=tn.translate(tn.identity(),a/i,h/n),v=tn.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,ti(this,Nn,"f"),e),y(t,ti(this,Bn,"f"),ti(this,jn,"f"),ti(this,Nn,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){kr._onLog&&kr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return kr._onLog&&kr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===fi.GREY?fi.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return kr._onLog&&kr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(kr._onLog&&(r=Date.now(),kr._onLog("transformPixelFormat(), START: "+r)),e===i)return kr._onLog&&kr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[fi.RGBA,fi.RBGA,fi.GRBA,fi.GBRA,fi.BRGA,fi.BGRA];if(o.includes(e))if(i===fi.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=kr._onLog)||void 0===n||n.call(kr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||fi.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(fi.GREY===y&&w.length{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Br{static get version(){return"4.2.3-dev-20250812165927"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find(t=>e.includes(t.label.toLowerCase()));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!r.length)return null;const s=r.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(s)return s.deviceId;const o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes($e.OS))return Br.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($e.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise(async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise(t=>{g=t}),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise(t=>{setTimeout(t,1e3)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}})}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!ti(this,er,"f"))return"closed";if("pending"===ti(this,er,"f"))return"opening";if("fulfilled"===ti(this,er,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Br.isStorageAvailable("localStorage")?ei(this,Jn,!0,"f"):(ei(this,Jn,!1,"f"),console.warn("Local storage is unavailable")):ei(this,Jn,!1,"f")}get ifSaveLastUsedCamera(){return ti(this,Jn,"f")}get isVideoPlaying(){return!(!ti(this,Yn,"f")||ti(this,Yn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=ti(this,ar,"f"))||void 0===e||e.removeEventListener("click",ti(this,or,"f")),null===(i=ti(this,ar,"f"))||void 0===i||i.removeEventListener("touchend",ti(this,or,"f")),null===(n=ti(this,ar,"f"))||void 0===n||n.removeEventListener("touchmove",ti(this,sr,"f")),ei(this,ar,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes($e.OS)?(t.addEventListener("touchend",ti(this,or,"f")),t.addEventListener("touchmove",ti(this,sr,"f"))):t.addEventListener("click",ti(this,or,"f")))}get tapFocusEventBoundEl(){return ti(this,ar,"f")}get disposed(){return ti(this,pr,"f")}constructor(t){var e,i;Wn.add(this),Yn.set(this,null),Hn.set(this,void 0),this._zoomPreSetting=null,Xn.set(this,()=>{"opened"===this.state&&ti(this,ur,"f").fire("resumed",null,{target:this,async:!1})}),zn.set(this,()=>{ti(this,ur,"f").fire("paused",null,{target:this,async:!1})}),qn.set(this,void 0),Kn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],Zn.set(this,void 0),Jn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,$n.set(this,void 0),Qn.set(this,!0),tr.set(this,void 0),er.set(this,void 0),ir.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},nr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(ti(this,Yn,"f")).objectFit,s=this.getResolution(),o=ti(this,Yn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=ti(this,Yn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},rr.set(this,!1),sr.set(this,()=>{ei(this,rr,!0,"f")}),or.set(this,async t=>{var e;if(ti(this,rr,"f"))return void ei(this,rr,!1,"f");if(!ti(this,nr,"f"))return;if(!this.isVideoPlaying)return;if(!ti(this,Hn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Br._onLog&&(c=Date.now());try{await ti(this,Wn,"m",Ir).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Br._onLog)throw Br._onLog(t),t}Br._onLog&&Br._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Br._onLog&&Br._onLog("Back to continuous focus."),null===(t=ti(this,Hn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),ti(this,ur,"f").fire("tapfocus",null,{target:this,async:!1})}),ar.set(this,null),hr.set(this,1),lr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!ti(this,Yn,"f"))return;const t=ti(this,hr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)ti(this,Yn,"f").style.transform="";else{const e=window.getComputedStyle(ti(this,Yn,"f")).objectFit,i=ti(this,Yn,"f").videoWidth,n=ti(this,Yn,"f").videoHeight,{width:r,height:s}=ti(this,Yn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-ti(this,lr,"f").x),c=h*(1-1/t)*(n/2-ti(this,lr,"f").y);ti(this,Yn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},cr.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===fi.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Br._onLog&&Br._onLog("document visible. video paused: "+(null===(t=ti(this,Yn,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Br._onLog&&Br._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Br._onLog&&Br._onLog("document visible. 1st resume video failed, try open instead.")}e||await ti(this,Wn,"m",Cr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Br._onLog&&Br._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Br._onLog&&Br._onLog("document visible. 2rd resume video failed, try open instead.")}e||await ti(this,Wn,"m",Cr).call(this)}}}else"hidden"===document.visibilityState&&(Br._onLog&&Br._onLog("document hidden. video paused: "+(null===(e=ti(this,Yn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),pr.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(()=>{Br.onWarning&&Br.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),ei(this,ur,new Ki,"f"),this.imageDataGetter=new kr,document.addEventListener("visibilitychange",ti(this,mr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",ti(this,Xn,"f")),t.addEventListener("pause",ti(this,zn,"f")),ei(this,Yn,t,"f")}getVideoEl(){return ti(this,Yn,"f")}releaseVideoEl(){var t,e;null===(t=ti(this,Yn,"f"))||void 0===t||t.removeEventListener("play",ti(this,Xn,"f")),null===(e=ti(this,Yn,"f"))||void 0===e||e.removeEventListener("pause",ti(this,zn,"f")),ei(this,Yn,null,"f")}isVideoLoaded(){return!!ti(this,Yn,"f")&&(this.videoSrc?0!==ti(this,Yn,"f").readyState:4===ti(this,Yn,"f").readyState)}async open(){if(ti(this,tr,"f")&&!ti(this,Qn,"f")){if("pending"===ti(this,er,"f"))return ti(this,tr,"f");if("fulfilled"===ti(this,er,"f"))return}ti(this,ur,"f").fire("before:open",null,{target:this}),await ti(this,Wn,"m",Cr).call(this),ti(this,ur,"f").fire("played",null,{target:this,async:!1}),ti(this,ur,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;ti(this,ur,"f").fire("before:close",null,{target:this});const t=ti(this,tr,"f");if(ti(this,Wn,"m",Sr).call(this),t&&"pending"===ti(this,er,"f")){try{await t}catch(t){}if(!1===ti(this,Qn,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}ei(this,tr,null,"f"),ei(this,er,null,"f"),ti(this,ur,"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.");ti(this,Yn,"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 ti(this,Yn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof ti(this,qn,"f").video&&(ti(this,qn,"f").video={}),delete ti(this,qn,"f").video.facingMode,ti(this,qn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&ti(this,Qn,"f"))){ti(this,ur,"f").fire("before:camera:change",[],{target:this,async:!1}),await ti(this,Wn,"m",Er).call(this);try{this.resetSoftwareScale()}catch(t){}return ti(this,Kn,"f")}}async switchToFrontCamera(t){if("object"!=typeof ti(this,qn,"f").video&&(ti(this,qn,"f").video={}),(null==t?void 0:t.resolution)&&(ti(this,qn,"f").video.width={ideal:t.resolution.width},ti(this,qn,"f").video.height={ideal:t.resolution.height}),delete ti(this,qn,"f").video.deviceId,ti(this,qn,"f").video.facingMode={exact:"user"},ei(this,Zn,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&ti(this,Qn,"f"))){ti(this,ur,"f").fire("before:camera:change",[],{target:this,async:!1}),ti(this,Wn,"m",Er).call(this);try{this.resetSoftwareScale()}catch(t){}return ti(this,Kn,"f")}}getCamera(){var t;if(ti(this,Kn,"f"))return ti(this,Kn,"f");{let e=(null===(t=ti(this,qn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"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 ti(this,qn,"f").video&&(ti(this,qn,"f").video={}),i?(ti(this,qn,"f").video.width={exact:t},ti(this,qn,"f").video.height={exact:e}):(ti(this,qn,"f").video.width={ideal:t},ti(this,qn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&ti(this,Qn,"f"))return null;ti(this,ur,"f").fire("before:resolution:change",[],{target:this,async:!1}),await ti(this,Wn,"m",Er).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&ti(this,Yn,"f"))return{width:ti(this,Yn,"f").videoWidth,height:ti(this,Yn,"f").videoHeight};if(ti(this,Hn,"f")){const t=ti(this,Hn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:ti(this,Yn,"f").videoWidth,height:ti(this,Yn,"f").videoHeight};{const t={width:0,height:0};let e=ti(this,qn,"f").video.width||0,i=ti(this,qn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=ti(this,fr,"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=ti(this,Kn,"f"))||void 0===u?void 0:u.deviceId;let e=ti(this,fr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],ti(this,fr,"f").set(d,e),ei(this,ir,!0,"f");try{for(let t of this.detectedResolutions){await ti(this,Hn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),ti(this,Wn,"m",vr).call(this);const i=ti(this,Hn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw ti(this,Wn,"m",Sr).call(this),ei(this,ir,!1,"f"),t}try{await ti(this,Wn,"m",Cr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{ei(this,ir,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=ti(this,qn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=ti(this,qn,"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=ti(this,qn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=ti(this,fr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],ti(this,fr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");ei(this,qn,JSON.parse(JSON.stringify(t)),"f"),ei(this,Zn,null,"f"),e&&await ti(this,Wn,"m",Er).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(ti(this,qn,"f")))}resetMediaStreamConstraints(){ei(this,qn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ti(this,Hn,"f").getCapabilities?ti(this,Hn,"f").getCapabilities():{}}getCameraSettings(){if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ti(this,Hn,"f").getSettings()}async turnOnTorch(){if(!ti(this,Hn,"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 ti(this,Hn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!ti(this,Hn,"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 ti(this,Hn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await ti(this,Hn,"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(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await ti(this,Hn,"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(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await ti(this,Hn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Nr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await ti(this,Hn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await ti(this,Wn,"m",Ir).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await ti(this,Hn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}enableTapToFocus(){ei(this,nr,!0,"f")}disableTapToFocus(){ei(this,nr,!1,"f")}isTapToFocusEnabled(){return ti(this,nr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"===this.state){t.centerPoint?ti(this,Wn,"m",xr).call(this,t.centerPoint):this.resetScaleCenter();try{if(ti(this,Wn,"m",Or).call(this,ti(this,lr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}else this._zoomPreSetting=t}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*ti(this,hr,"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(!ti(this,Hn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Nr(t,n.min,n.step,n.max)),await ti(this,Hn,"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&&ti(this,Wn,"m",xr).call(this,e),ei(this,hr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return ti(this,hr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();ei(this,lr,{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(ti(this,ir,"f"))return null;const e=Date.now();Br._onLog&&Br._onLog("getFrameData() START: "+e);const i=ti(this,Yn,"f").videoWidth,n=ti(this,Yn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=fi.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=ti(this,hr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=ti(this,lr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(ti(this,Yn,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Br._onLog&&Br._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:ti(this,cr,"f")}}on(t,e){if(!ti(this,dr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);ti(this,ur,"f").on(t,e)}off(t,e){ti(this,ur,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),ti(this,ur,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",ti(this,mr,"f")),ei(this,pr,!0,"f")}}var jr,Ur,Vr,Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws;Yn=new WeakMap,Hn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,Wn=new WeakSet,_r=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(ti(this,Zn,"f"))delete t.video.facingMode,t.video.deviceId={exact:ti(this,Zn,"f")};else if(this.ifSaveLastUsedCamera&&Br.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($e.OS)?(await this._getCameras(!1),ti(this,Wn,"m",vr).call(this),e=Br.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes($e.OS)||(await this._getCameras(!1),ti(this,Wn,"m",vr).call(this),e=Br.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},vr=function(){if(ti(this,Qn,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},yr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Br._onLog&&Br._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise(t=>setTimeout(t,r)),ti(this,Wn,"m",vr).call(this));try{Br._onLog&&Br._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),ti(this,Wn,"m",vr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Br._onLog&&Br._onLog(t.message||t)}}};if(await r(t),!n&&"object"==typeof t.video&&(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t)),!n)){const t=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let e of t){const t={video:{deviceId:{ideal:e.deviceId},facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}}};if(await r(t),n)break}}if(!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach(t=>{t.stop()}),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},wr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),ei(this,Hn,null,"f")},Cr=async function(){ei(this,Qn,!1,"f");const t=ei(this,$n,Symbol(),"f");if(ti(this,tr,"f")&&"pending"===ti(this,er,"f")){try{await ti(this,tr,"f")}catch(t){}ti(this,Wn,"m",vr).call(this)}if(t!==ti(this,$n,"f"))return;const e=ei(this,tr,(async()=>{ei(this,er,"pending","f");try{if(this.videoSrc){if(!ti(this,Yn,"f"))throw new Error("'videoEl' should be set.");await Br.playVideo(ti(this,Yn,"f"),this.videoSrc,this.cameraOpenTimeout),ti(this,Wn,"m",vr).call(this)}else{let t=await ti(this,Wn,"m",_r).call(this);ti(this,Wn,"m",wr).call(this);let e=await ti(this,Wn,"m",yr).call(this,t);await this._getCameras(!1),ti(this,Wn,"m",vr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=ti(this,qn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(ti(this,Zn,"f")||this.ifSaveLastUsedCamera&&Br.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Br.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:s},e=await ti(this,Wn,"m",yr).call(this,t),ti(this,Wn,"m",vr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(ei(this,Zn,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Br.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",ti(this,Zn,"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))))),ti(this,Yn,"f")&&(await Br.playVideo(ti(this,Yn,"f"),e,this.cameraOpenTimeout),ti(this,Wn,"m",vr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&ei(this,Hn,s[0],"f"),ei(this,Kn,r,"f")}}catch(t){throw ti(this,Wn,"m",Sr).call(this),ei(this,er,null,"f"),t}ei(this,er,"fulfilled","f")})(),"f");return e},Er=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=ti(this,Kn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await ti(this,Wn,"m",Cr).call(this);const n=this.getResolution();e&&e!==ti(this,Kn,"f").deviceId&&ti(this,ur,"f").fire("camera:changed",[ti(this,Kn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||ti(this,ur,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),ti(this,ur,"f").fire("played",null,{target:this,async:!1})},Sr=function(){ti(this,Wn,"m",wr).call(this),ei(this,Kn,null,"f"),ti(this,Yn,"f")&&(ti(this,Yn,"f").srcObject=null,this.videoSrc&&(ti(this,Yn,"f").pause(),ti(this,Yn,"f").currentTime=0)),ei(this,Qn,!0,"f");try{this.resetSoftwareScale()}catch(t){}},br=async function t(e,i){const n=t=>{if(!ti(this,Hn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){ti(this,Hn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Nr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await ti(this,Hn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise(t=>{setTimeout(t,r)}),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(ti(this,Yn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:fi.RGBA,bufferContainer:d}))return ti(this,Wn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await ti(this,Wn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await ti(this,Wn,"m",br).call(this,e,c);if(a>h)return await ti(this,Wn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await ti(this,Wn,"m",t).call(this,e,o,a,c,h);let u=await ti(this,Wn,"m",br).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!==ti(this,hr,"f")){const t=ti(this,hr,"f"),e=ti(this,lr,"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 n=Nr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Nr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Nr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await ti(this,Wn,"m",br).call(this,t,s),a=await ti(this,Wn,"m",br).call(this,t,r),h=await ti(this,Wn,"m",br).call(this,t,n);if(a>h&&ho&&a>o){let e=await ti(this,Wn,"m",br).call(this,t,i);const r=await ti(this,Wn,"m",Tr).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await ti(this,Wn,"m",Tr).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},xr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");ei(this,lr,{x:i,y:n},"f")},Or=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},Br.browserInfo=$e,Br.onWarning=null===(Gn=null===window||void 0===window?void 0:window.console)||void 0===Gn?void 0:Gn.warn;class Cs{constructor(t){jr.add(this),Ur.set(this,void 0),Vr.set(this,0),Gr.set(this,void 0),Wr.set(this,0),Yr.set(this,!1),ei(this,Ur,t,"f")}startCharging(){ti(this,Yr,"f")||(Cs._onLog&&Cs._onLog("start charging."),ti(this,jr,"m",Xr).call(this),ei(this,Yr,!0,"f"))}stopCharging(){ti(this,Gr,"f")&&clearTimeout(ti(this,Gr,"f")),ti(this,Yr,"f")&&(Cs._onLog&&Cs._onLog("stop charging."),ei(this,Vr,Date.now()-ti(this,Wr,"f"),"f"),ei(this,Yr,!1,"f"))}}Ur=new WeakMap,Vr=new WeakMap,Gr=new WeakMap,Wr=new WeakMap,Yr=new WeakMap,jr=new WeakSet,Hr=function(){Yt.cfd(1),Cs._onLog&&Cs._onLog("charge 1.")},Xr=function t(){0==ti(this,Vr,"f")&&ti(this,jr,"m",Hr).call(this),ei(this,Wr,Date.now(),"f"),ti(this,Gr,"f")&&clearTimeout(ti(this,Gr,"f")),ei(this,Gr,setTimeout(()=>{ei(this,Vr,0,"f"),ti(this,jr,"m",t).call(this)},ti(this,Ur,"f")-ti(this,Vr,"f")),"f")};class Es{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-ti(this,zr,"f",Zr)<100)){if(ei(this,zr,e,"f",Zr),ti(this,zr,"f",qr).size&&(t=ti(this,zr,"f",qr).values().next().value,this.beepSoundSource==t.src?(ti(this,zr,"f",qr).delete(t),t.play()):t=null),!t)if(ti(this,zr,"f",Kr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{ti(this,zr,"f",Kr).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,ti(this,zr,"f",Kr).delete(t),ti(this,zr,"f",qr).add(t)})}else ti(this,zr,"f",Jr)||(ei(this,zr,!0,"f",Jr),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&ti(this,zr,"f",Kr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Es.vibrateDuration)}}}zr=Es,qr={value:new Set},Kr={value:new Set},Zr={value:0},Jr={value:!1},Es.allowBeep=!0,Es.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Es.allowVibrate=!0,Es.vibrateDuration=300;const Ss=new Map([[fi.GREY,_.IPF_GRAYSCALED],[fi.RGBA,_.IPF_ABGR_8888]]),bs="function"==typeof BigInt?t=>BigInt(t):t=>t,Ts=(bs("0x00"),bs("0xFFFFFFFFFFFFFFFF"),bs("0xFE3BFFFF"),bs("0x003007FF")),Is=(bs("0x0003F800"),bs("0x1"),bs("0x2"),bs("0x4"),bs("0x8"),bs("0x10"),bs("0x20"),bs("0x40"),bs("0x80"),bs("0x100"),bs("0x200"),bs("0x400"),bs("0x800"),bs("0x1000"),bs("0x2000"),bs("0x4000"),bs("0x8000"),bs("0x10000"),bs("0x20000"),bs("0x00040000"),bs("0x01000000"),bs("0x02000000"),bs("0x04000000")),xs=bs("0x08000000");bs("0x10000000"),bs("0x20000000"),bs("0x40000000"),bs("0x00080000"),bs("0x80000000"),bs("0x100000"),bs("0x200000"),bs("0x400000"),bs("0x800000"),bs("0x1000000000"),bs("0x3F0000000000000"),bs("0x100000000"),bs("0x10000000000000"),bs("0x20000000000000"),bs("0x40000000000000"),bs("0x80000000000000"),bs("0x100000000000000"),bs("0x200000000000000"),bs("0x200000000"),bs("0x400000000"),bs("0x800000000"),bs("0xC00000000"),bs("0x2000000000"),bs("0x4000000000");class Os extends ht{static set _onLog(t){ei(Os,Qr,t,"f",ts),Br._onLog=t,Cs._onLog=t}static get _onLog(){return ti(Os,Qr,"f",ts)}static async detectEnvironment(){return await(async()=>({wasm:ii,worker:ni,getUserMedia:ri,camera:await si(),browser:$e.browser,version:$e.version,OS:$e.OS}))()}static async testCameraAccess(){const t=await Br.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 Pr))throw new TypeError("Invalid view.");if(!Os._isRTU&&(null===(e=Vt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=Vt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await Yt.loadWasm(),await Vt.license.dynamsoft()}const n=new Os(t);return Os.onWarning&&(location&&"file:"===location.protocol?setTimeout(()=>{Os.onWarning&&Os.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(()=>{Os.onWarning&&Os.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})},0)),n}get isEnableMirroring(){return this._isEnableMirroring}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");ei(this,rs,t,"f")}get singleFrameMode(){return ti(this,rs,"f")}get _isFetchingStarted(){return ti(this,cs,"f")}get disposed(){return ti(this,ms,"f")}constructor(t){if(super(),$r.add(this),es.set(this,"closed"),is.set(this,void 0),ns.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,rs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ss.set(this,(t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?fi.GREY:fi.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===fi.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:Ss.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:ti(this,os,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Xi.convert(ti(this,hs,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=ti(this,ss,"f").call(this,t,t.width,t.height,e);ti(this,is,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},os.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===_.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes($e.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",()=>{ti(this,gs,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("camera:changed",()=>{this.clearBuffer()}),this._on("before:resolution:change",()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("resolution:changed",()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})}),this._on("paused",()=>{ti(this,gs,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{ti(this,ds,"f").tapToFocus&&ti(this,gs,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(ti(this,$r,"m",ps).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Os._onLog&&(Os._onLog("intermediateResultUnits:"),Os._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Et.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Et.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Os._onLog&&(Os._onLog("hasLocalizedBarcodes:"),Os._onLog(h)),ti(this,ds,"f").autoZoom||ti(this,ds,"f").enhancedFocus)if(a)ti(this,fs,"f").autoZoomInFrameArray.length=0,ti(this,fs,"f").autoZoomOutFrameCount=0,ti(this,fs,"f").frameArrayInIdealZoom.length=0,ti(this,fs,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),ti(this,ds,"f").autoZoom&&ti(this,gs,"f").startCharging()},a=async t=>{await this.setFocus(t),ti(this,ds,"f").enhancedFocus&&ti(this,gs,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-ti(this,fs,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+ti(this,fs,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-ti(this,fs,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+ti(this,fs,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Os._onLog&&(Os._onLog("detectionArea:"),Os._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Ji(a.y-i)>0&&Ji(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!($i([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||$i([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||$i([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||$i([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Pr._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Os._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Rr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Fi({points:i},e);t.addDrawingItems([r])}}}if(Os._onLog&&(Os._onLog("intersectedResults:"),Os._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==Is||t.possibleFormats==xs);if(t.length||(t=s.filter(t=>t.possibleFormats==Ts),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{}),ti(this,fs,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=ti(this,fs,"f").autoZoomInFrameLimit[1]){ti(this,fs,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,ti(this,fs,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/ti(this,fs,"f").autoZoomInMaxTimes),ti(this,fs,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(ti(this,fs,"f").minValue,u),u=Math.min(ti(this,fs,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(ti(this,fs,"f").autoZoomInFrameArray.length=0,ti(this,fs,"f").frameArrayInIdealZoom.push(!0),ti(this,fs,"f").frameArrayInIdealZoom.splice(0,ti(this,fs,"f").frameArrayInIdealZoom.length-ti(this,fs,"f").frameLimitInIdealZoom[0]),ti(this,fs,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=ti(this,fs,"f").frameLimitInIdealZoom[1]&&(ti(this,fs,"f").frameArrayInIdealZoom.length=0,ti(this,ds,"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(!ti(this,ds,"f").autoZoom&&ti(this,ds,"f").enhancedFocus&&(ti(this,fs,"f").autoFocusFrameArray.push(!0),ti(this,fs,"f").autoFocusFrameArray.splice(0,ti(this,fs,"f").autoFocusFrameArray.length-ti(this,fs,"f").autoFocusFrameLimit[0]),ti(this,fs,"f").autoFocusFrameArray.filter(t=>!0===t).length>=ti(this,fs,"f").autoFocusFrameLimit[1])){ti(this,fs,"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(ti(this,ds,"f").autoZoom){if(ti(this,fs,"f").autoZoomInFrameArray.push(!1),ti(this,fs,"f").autoZoomInFrameArray.splice(0,ti(this,fs,"f").autoZoomInFrameArray.length-ti(this,fs,"f").autoZoomInFrameLimit[0]),ti(this,fs,"f").autoZoomOutFrameCount++,ti(this,fs,"f").frameArrayInIdealZoom.push(!1),ti(this,fs,"f").frameArrayInIdealZoom.splice(0,ti(this,fs,"f").frameArrayInIdealZoom.length-ti(this,fs,"f").frameLimitInIdealZoom[0]),ti(this,fs,"f").autoZoomOutFrameCount>=ti(this,fs,"f").autoZoomOutFrameLimit){ti(this,fs,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*ti(this,fs,"f").autoZoomOutStepRate,ti(this,fs,"f").autoZoomOutMinStep);n=Math.max(ti(this,fs,"f").minValue,n),n=Math.min(ti(this,fs,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}ti(this,ds,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!ti(this,ds,"f").autoZoom&&ti(this,ds,"f").enhancedFocus&&(ti(this,fs,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},ei(this,gs,new Cs(1e4),"f")}setCameraView(t){if(!(t instanceof Pr))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),ti(this,$r,"m",ps).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;ti(this,$r,"m",ps).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return ti(this,$r,"m",ps).call(this)?ti(this,es,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,ti(this,$r,"m",ps).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(ti(this,$r,"m",ps).call(this));else{try{await this.cameraManager.open(),ei(this,ns,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=Es.allowBeep?"":"none"),a&&(a.style.display=Es.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=Es.allowVibrate?"":"none"),l&&(l.style.display=Es.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const C=()=>{Es.allowBeep=!Es.allowBeep,o&&(o.style.display=Es.allowBeep?"":"none"),a&&(a.style.display=Es.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",C);const E=()=>{Es.allowVibrate=!Es.allowVibrate,h&&(h.style.display=Es.allowVibrate?"":"none"),l&&(l.style.display=Es.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",E);const S=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==$e?void 0:$e.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",C);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",E);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return ei(this,es,"open","f"),e&&(e._innerComponent.style.display="",ti(this,$r,"m",ps).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),ti(this,is,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),ti(this,$r,"m",ps).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}ei(this,es,"closed","f"),ti(this,gs,"f").stopCharging(),e&&(e._innerComponent.style.display="none",ti(this,$r,"m",ps).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),ti(this,is,"f").fire("closed",null,{target:this,async:!1})}pause(){if(ti(this,$r,"m",ps).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!ti(this,$r,"m",ps).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(ti(this,$r,"m",ps).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch(()=>{});const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),this.toggleMirroring(this._isEnableMirroring),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ti(this,is,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ti(this,is,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(ti(this,$r,"m",ps).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(ti(this,$r,"m",ps).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(_.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Os._onLog)||void 0===t||t.call(Os,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(ti(this,$r,"m",ps).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(ti(this,$r,"m",ps).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(ti(this,$r,"m",ps).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(ti(this,$r,"m",ps).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(ti(this,$r,"m",ps).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(ti(this,$r,"m",ps).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){ti(this,fs,"f").minValue=t.min,ti(this,fs,"f").maxValue=t.max}getAutoZoomRange(){return{min:ti(this,fs,"f").minValue,max:ti(this,fs,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=Vt.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!==Yt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&di.EF_ENHANCED_FOCUS&&(ti(this,ds,"f").enhancedFocus=!0),t&di.EF_AUTO_ZOOM&&(ti(this,ds,"f").autoZoom=!0),t&di.EF_TAP_TO_FOCUS&&(ti(this,ds,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&di.EF_ENHANCED_FOCUS&&(ti(this,ds,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&di.EF_AUTO_ZOOM&&(ti(this,ds,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&di.EF_TAP_TO_FOCUS&&(ti(this,ds,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),ti(this,$r,"m",vs).call(this)&&ti(this,$r,"m",_s).call(this)||ti(this,gs,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");ei(this,hs,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(ti(this,hs,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");ei(this,as,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||ti(this,$r,"m",ps).call(this))}startFetching(){if(ti(this,$r,"m",ps).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");ti(this,cs,"f")||(ei(this,cs,!0,"f"),ti(this,$r,"m",ys).call(this))}stopFetching(){ti(this,cs,"f")&&(Os._onLog&&Os._onLog("DCE: stop fetching loop: "+Date.now()),ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),ei(this,cs,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(ti(this,$r,"m",ps).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i;if(i=Xi.convert(ti(this,hs,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y);const n=this.cameraView.regionMaskLineWidth;let r;r=ti(this,hs,"f")&&!t?{sx:i.x+n,sy:i.y+n,sWidth:i.width-2*n,sHeight:i.height-2*n,dWidth:i.width-2*n,dHeight:i.height-2*n}:{sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};const s=Math.max(r.dWidth,r.dHeight);if(this.canvasSizeLimit&&s>this.canvasSizeLimit){const t=this.canvasSizeLimit/s;r.dWidth>r.dHeight?(r.dWidth=this.canvasSizeLimit,r.dHeight=Math.round(r.dHeight*t)):(r.dWidth=Math.round(r.dWidth*t),r.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.getFrameData({position:r,pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?fi.GREY:fi.RGBA,isEnableMirroring:this._isEnableMirroring});if(!o)return null;let a;a=o.pixelFormat===fi.GREY?o.width:4*o.width;let h=!0;return 0===r.sx&&0===r.sy&&r.sWidth===e.width&&r.sHeight===e.height&&(h=!1),{bytes:o.data,width:o.width,height:o.height,stride:a,format:Ss.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_VIDEO_FRAME,isCropped:h,cropRegion:{left:r.sx,top:r.sy,right:r.sx+r.sWidth,bottom:r.sy+r.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:o.width,currentHeight:o.height,timeSpent:o.timeSpent,timeStamp:o.timeStamp},toCanvas:ti(this,os,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,ti(this,cs,"f")&&(ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),ei(this,us,setTimeout(()=>{this.disposed||ti(this,$r,"m",ys).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){ei(this,ls,t,"f")}getPixelFormat(){return ti(this,ls,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(ti(this,$r,"m",ps).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",()=>{t&&this.open(),e.remove()},{once:!0})}),e.addEventListener("change",async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=Xi.convert(ti(this,hs,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=ti(this,ss,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=ti(this,$r,"m",ws).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=ti(this,$r,"m",ws).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!ti(this,hs,"f"))return JSON.parse(JSON.stringify(t));if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});ei(this,ns,t||ti(this,ns,"f"),"f")}let e,i,n=ti(this,hs,"f").left||ti(this,hs,"f").x||0,r=ti(this,hs,"f").top||ti(this,hs,"f").y||0;if(!ti(this,hs,"f").isMeasuredInPercentage)return{x:t.x-(n+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").x),y:t.y-(r+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").y)};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ti(this,$r,"m",ps).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ti(this,$r,"m",ps).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(ti(this,$r,"m",ps).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else e=ti(this,ns,"f").width,i=ti(this,ns,"f").height;return{x:t.x-(Math.round(n*e/100)+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").x),y:t.y-(Math.round(r*i/100)+this.cameraView.regionMaskLineWidth+ti(this,ns,"f").y)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),ei(this,ms,!0,"f")}}var Rs,As,Ds,Ls,Ms,Fs,Ps,ks;Qr=Os,es=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,$r=new WeakSet,ps=function(){return"disabled"!==this.singleFrameMode},_s=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},vs=function(){for(let t in ti(this,ds,"f"))if(1==ti(this,ds,"f")[t])return!0;return!1},ys=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!ti(this,cs,"f"))return ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),void ei(this,us,setTimeout(()=>{this.disposed||ti(this,$r,"m",t).call(this)},this.fetchInterval),"f");const e=()=>{var t;let e;Os._onLog&&Os._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=ti(this,as,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=ti(this,as,"f"))||void 0===t||t.onErrorReceived(mt.EC_IMAGE_READ_FAILED,i)},0);console.warn(e)}e?(this.addImageToBuffer(e),Os._onLog&&Os._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),ti(this,is,"f").fire("frameAddedToBuffer",null,{async:!1})):Os._onLog&&Os._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case m.BOPM_BLOCK:break;case m.BOPM_UPDATE:e()}else e();ti(this,us,"f")&&clearTimeout(ti(this,us,"f")),ei(this,us,setTimeout(()=>{this.disposed||ti(this,$r,"m",t).call(this)},this.fetchInterval),"f")},ws=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ti(this,$r,"m",ps).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ti(this,$r,"m",ps).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(ti(this,$r,"m",ps).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(ti(this,Ls,"f")||ei(this,Ls,new Ns,"f"),!ti(this,Ls,"f").magnifierCanvas)return;document.body.contains(ti(this,Ls,"f").magnifierCanvas)||(ti(this,Ls,"f").magnifierCanvas.style.position="fixed",ti(this,Ls,"f").magnifierCanvas.style.boxSizing="content-box",ti(this,Ls,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(ti(this,Ls,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void ti(this,Fs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];ti(this,Ls,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(ti(this,Ls,"f").magnifierCanvas.style.left="auto",ti(this,Ls,"f").magnifierCanvas.style.top="0",ti(this,Ls,"f").magnifierCanvas.style.right="0"):(ti(this,Ls,"f").magnifierCanvas.style.left="0",ti(this,Ls,"f").magnifierCanvas.style.top="0",ti(this,Ls,"f").magnifierCanvas.style.right="auto")}ti(this,Ls,"f").show()}),Fs.set(this,()=>{ti(this,Ls,"f")&&ti(this,Ls,"f").hide()}),Ps.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(A(t)){ei(this,Ds,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===_.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Vs){if(!js&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Ws=t=>t&&"object"==typeof t&&"function"==typeof t.then,Ys=(async()=>{})().constructor;let Hs=class extends Ys{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,Ws(t)?e=t:"function"==typeof t&&(e=new Ys(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Ws(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Xs=" is not allowed to change after `createInstance` or `loadWasm` is called.",zs=!js&&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"))||"",qs=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Xs);i._license=e}};!js&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ks=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Ks(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Xs);i._licenseServer=e}},Js=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Xs);i._deviceFriendlyName=e}};let $s,Qs,to,eo,io;"undefined"!=typeof navigator&&($s=navigator,Qs=$s.userAgent,to=$s.platform,eo=$s.mediaDevices),function(){if(!js){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:$s.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:to,search:"Win"},Mac:{str:to},Linux:{str:to}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Qs,o=r.search||e,a=r.verStr||Qs,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Qs,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Qs.indexOf("Windows NT")&&(r="HarmonyOS"),io={browser:i,version:n,OS:r}}js&&(io={browser:"ssr",version:0,OS:"ssr"})}(),eo&&eo.getUserMedia,"Chrome"===io.browser&&io.version>66||"Safari"===io.browser&&io.version>13||"OPR"===io.browser&&io.version>43||"Edge"===io.browser&&io.version;const no=()=>(Yt.loadWasm(),Dt("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=so;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=Ks(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Us.crypto||(s="Please upgrade your browser to support online key."),Us.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Xs)})(),o=new Hs;so._pLoad.task=o,(async()=>{try{await so._pLoad}catch(t){}})();let a=Ft();Pt[a]=e=>{if(e.message&&so._onAuthMessage){let t=so._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(kt&&kt("init license success"),e.message&&console.warn(e.message),Yt._bSupportIRTModule=e.bSupportIRTModule,Yt._bSupportDce4Module=e.bSupportDce4Module,so.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=V(Yt.engineResourcePaths),i=("DCV"===Yt._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:so._bNeverShowDialog,engineResourcePath:i,_onLog:kt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await At("core"),Lt.postMessage({type:"license_dynamsoft",body:{v:"4.0.60-dev-20250812170103",brtk:!!t,bptk:1===t,l:e,os:io,fn:so.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),so.bCallInitLicense=!0,await o}));let ro;Vt.license={},Vt.license.dynamsoft=no,Vt.license.getAR=async()=>{{let t=Rt.dynamsoft_inited;t&&t.isRejected&&await t}return Lt?new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){delete i.success;{let t=so.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)}},Lt.postMessage({type:"license_getAR",id:i})}):null};let so=class t{static setLicenseServer(e){Zs(t,e)}static get license(){return this._license}static set license(e){qs(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Zs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Js(t,e)}static initLicense(e,i){if(qs(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return no()}static setDeviceFriendlyName(e){Js(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await Dt("dynamsoft_uuid",async()=>{await Yt.loadWasm();let t=new Hs,e=Ft();Pt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Lt.postMessage({type:"license_getDeviceUUID",id:e}),ro=await t}),ro))()}};so._pLoad=new Hs,so.bPassValidation=!1,so.bCallInitLicense=!1,so._license=zs,so._licenseServer=[],so._deviceFriendlyName="",Yt.engineResourcePaths.license={version:"4.0.60-dev-20250812170103",path:Gs,isInternal:!0},Gt.license={wasm:!0,js:!0},Vt.license.LicenseManager=so;const oo="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,oo)<0&&(Yt.engineResourcePaths.std={version:oo,path:(t=>{if(null==t&&(t="./"),js||Vs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Gs+`../../dynamsoft-capture-vision-std@${oo}/dist/`),isInternal:!0});let ao=class{static getVersion(){return`4.0.60-dev-20250812170103(Worker: ${Ut.license&&Ut.license.worker||"Not Loaded"}, Wasm: ${Ut.license&&Ut.license.wasm||"Not Loaded"})`}};const ho=()=>window.matchMedia("(orientation: landscape)").matches,lo=t=>Object.prototype.toString.call(t).slice(8,-1);function co(t,e){for(const i in e)"Object"===lo(e[i])&&i in t?co(t[i],e[i]):t[i]=e[i];return t}function uo(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function fo(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;ie.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const mo="undefined"==typeof self,po="function"==typeof importScripts,_o=(()=>{if(!po){if(!mo&&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"./"}})(),vo=t=>{if(null==t&&(t="./"),mo||po);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Yt.engineResourcePaths.utility={version:"2.0.60-dev-20250812170132",path:_o,isInternal:!0},Gt.utility={js:!0,wasm:!0};const yo="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,yo)<0&&(Yt.engineResourcePaths.std={version:yo,path:vo(_o+`../../dynamsoft-capture-vision-std@${yo}/dist/`),isInternal:!0});const wo="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,wo)<0)&&(Yt.engineResourcePaths.dip={version:wo,path:vo(_o+`../../dynamsoft-image-processing@${wo}/dist/`),isInternal:!0});let Co=class{static getVersion(){return`2.0.60-dev-20250812170132(Worker: ${Ut.utility&&Ut.utility.worker||"Not Loaded"}, Wasm: ${Ut.utility&&Ut.utility.wasm||"Not Loaded"})`}};function Eo(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const So="undefined"==typeof self,bo="function"==typeof importScripts,To=(()=>{if(!bo){if(!So&&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"./"}})(),Io=t=>{if(null==t&&(t="./"),So||bo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Yt.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:To,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const xo="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,xo)<0&&(Yt.engineResourcePaths.std={version:xo,path:Io(To+`../../dynamsoft-capture-vision-std@${xo}/dist/`),isInternal:!0});const Oo="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,Oo)<0)&&(Yt.engineResourcePaths.dip={version:Oo,path:Io(To+`../../dynamsoft-image-processing@${Oo}/dist/`),isInternal:!0});const Ro={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Ao,Do,Lo,Mo,Fo,Po,ko,No,Bo,jo;function Uo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Wo(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Xo(t){let e=0;for(let i=0;i0}function qo(t,e){for(let i=0;i<4;i++)if(!zo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}(Fo=Ao||(Ao={}))[Fo.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",Fo[Fo.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",Fo[Fo.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Do||(Do={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(Lo||(Lo={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(Mo||(Mo={}));function Ko(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Wo(r)[3],h=Wo(r)[1],l=Wo(s)[3],c=Wo(s)[1];let u,d=0;if(u=Math.max(Math.abs(Go(a,e.points[0])),Math.abs(Go(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Go(h,e.points[1])),Math.abs(Go(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Go(l,t.points[0])),Math.abs(Go(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Go(c,t.points[1])),Math.abs(Go(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Yo(Wo(r)[0]),g=Yo(Wo(r)[2]),m=Yo(Wo(s)[0]),p=Yo(Wo(s)[2]),_=Vo(f,p),v=Vo(m,g),y=_>v,w=Math.min(_,v),C=Vo(f,g),E=Vo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(qo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(qo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(qo(t,this.location.points[e]))return!0;if(qo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Go(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Ho(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{Uo(e,t)&&i.push(t)}),e.forEach(e=>{Uo(t,e)&&i.push(e)}),Xo(function(t){if(t.length<=1)return t;t.sort((t,e)=>t.x-e.x||t.y-e.y);const e=t.shift();return t.sort((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x)),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Jo={barcode:2,text_line:4,detected_quad:8,deskewed_image:16},$o=t=>Object.values(Jo).includes(t)||Jo.hasOwnProperty(t),Qo=(t,e)=>"string"==typeof t?e[Jo[t]]:e[t],ta=(t,e,i)=>{"string"==typeof t?e[Jo[t]]=i:e[t]=i},ea=(t,e,i)=>{const n=[{type:ft.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:ft.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class ia{constructor(){this.verificationEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!0,[ft.CRIT_DETECTED_QUAD]:!0,[ft.CRIT_DESKEWED_IMAGE]:!1},this.duplicateFilterEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},this.duplicateForgetTime={[ft.CRIT_BARCODE]:3e3,[ft.CRIT_TEXT_LINE]:3e3,[ft.CRIT_DETECTED_QUAD]:3e3,[ft.CRIT_DESKEWED_IMAGE]:3e3},this.latestOverlappingEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[ft.CRIT_BARCODE]:5,[ft.CRIT_TEXT_LINE]:5,[ft.CRIT_DETECTED_QUAD]:5,[ft.CRIT_DESKEWED_IMAGE]:5},this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,Po.set(this,new Map),ko.set(this,new Map),No.set(this,new Map),Bo.set(this,new Map),jo.set(this,new Map),Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),ea(this,t,ft.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{ea(this,t,ft.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){Eo(this,Po,"f").forEach((t,e)=>{ta(e,this.verificationEnabled,t)}),Eo(this,ko,"f").forEach((t,e)=>{ta(e,this.duplicateFilterEnabled,t)}),Eo(this,No,"f").forEach((t,e)=>{ta(e,this.duplicateForgetTime,t)}),Eo(this,Bo,"f").forEach((t,e)=>{ta(e,this.latestOverlappingEnabled,t)}),Eo(this,jo,"f").forEach((t,e)=>{ta(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){$o(t)&&Eo(this,Po,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!$o(t)&&Qo(t,this.verificationEnabled)}enableResultDeduplication(t,e){$o(t)&&(e&&this.enableLatestOverlapping(t,!1),Eo(this,ko,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!$o(t)&&Qo(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){$o(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Eo(this,No,"f").set(t,e))}getDuplicateForgetTime(t){return $o(t)?Qo(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){$o(t)&&Eo(this,jo,"f").set(t,e)}getMaxOverlappingFrames(t){return $o(t)?Qo(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){$o(t)&&(e&&this.enableResultDeduplication(t,!1),Eo(this,Bo,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!$o(t)&&Qo(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[ft.CRIT_BARCODE,ft.CRIT_TEXT_LINE,ft.CRIT_DETECTED_QUAD,ft.CRIT_DESKEWED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ro.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ro.BF_GS1_DATABAR))!=BigInt(0);return new Zo(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ro.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ro.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}f.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),d.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}Po=new WeakMap,ko=new WeakMap,No=new WeakMap,Bo=new WeakMap,jo=new WeakMap;const na=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:_.IPF_ABGR_8888}};var ra,sa,oa,aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ca,Ea,Sa,ba,Ta,Ia,xa,Oa,Ra,Aa,Da,La,Ma;class Fa{async readFromFile(t){return await na(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=X(t);return G(n,e,i)}async readFromMemory(t){if(!Eo(Fa,ra,"f",sa).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=Eo(Fa,ra,"f",sa).get(t);return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{var i,n;if(e.success)return function(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");r?r.value=i:e.set(t,i)}(i=Fa,ra,(n=Eo(i,ra,"f",oa),++n),0,oa),Eo(Fa,ra,"f",sa).set(Eo(Fa,ra,"f",oa),JSON.parse(e.memery)),t(Eo(Fa,ra,"f",oa));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}ra=Fa,sa={value:new Map},oa={value:0};class Pa{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await na(t);else if("string"==typeof t){let e=await B(t,"blob");a=await na(e)}else A(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return o&&(new Fa).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}}class ka{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await na(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await na(t);return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await na(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await na(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}}!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(aa||(aa={}));class Na{constructor(t){if(ha.add(this),ua.set(this,void 0),da.set(this,{status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]}),fa.set(this,!1),ga.set(this,void 0),ma.set(this,void 0),pa.set(this,void 0),_a.set(this,void 0),this.config=fo(Ht),t&&"object"!=typeof t||Array.isArray(t))throw"Invalid config.";co(this.config,t),Os._isRTU=!0}get disposed(){return e(this,fa,"f")}launch(){return t(this,void 0,void 0,function*(){if(e(this,fa,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(e(Na,la,"f",ca)&&!e(Na,la,"f",ca).isFulfilled&&!e(Na,la,"f",ca).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return i(Na,la,new qt,"f",ca),yield e(this,ha,"m",va).call(this),e(Na,la,"f",ca)})}decode(n,r="ReadBarcodes_Default"){return t(this,void 0,void 0,function*(){i(this,ma,r,"f"),yield e(this,ha,"m",ya).call(this,!0),e(this,_a,"f")||i(this,_a,new ia,"f"),e(this,_a,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(e(this,_a,"f"));const t=new Ge;t.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(t);const s=yield this._cvRouter.capture(n,r);return e(this,_a,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(e(this,_a,"f")),this._cvRouter.removeResultReceiver(t),s})}dispose(){var t,n,r,s,o,a,h;i(this,fa,!0,"f"),e(Na,la,"f",ca)&&e(Na,la,"f",ca).isPending&&e(Na,la,"f",ca).resolve(e(this,da,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(n=this._cameraView)||void 0===n||n.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",e(this,ua,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}la=Na,ua=new WeakMap,da=new WeakMap,fa=new WeakMap,ga=new WeakMap,ma=new WeakMap,pa=new WeakMap,_a=new WeakMap,ha=new WeakSet,va=function(){return t(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield e(this,ha,"m",ya).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),uo(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){e(this,ha,"m",Aa).call(this),e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,ma,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(t){e(this,da,"f").status={code:l.RS_FAILED,message:t.message||t},e(Na,la,"f",ca).reject(new Error(e(this,da,"f").status.message)),this.dispose()}finally{e(this,ha,"m",La).call(this,"Loading...",!1)}})},ya=function(n=!1){return t(this,void 0,void 0,function*(){if(Yt.engineResourcePaths=this.config.engineResourcePaths,!n){const t=V(Yt.engineResourcePaths);if(this._cameraView=yield Pr.createInstance(t.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this.config.scanMode===a.SM_SINGLE&&(this._cameraView._capturedResultReceiver.onCapturedResultReceived=()=>{}),this._cameraEnhancer=yield Os.createInstance(this._cameraView),this.disposed)return;if(yield e(this,ha,"m",Ca).call(this),this.disposed)return;if(this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1),i(this,pa,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}}yield so.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield Ve.createInstance()),this.disposed||(this.config.scanMode!==a.SM_SINGLE||n?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{e(Na,la,"f",ca).reject(new Error(t.message)),this.dispose()},yield e(this,ha,"m",wa).call(this,n),this.disposed||n||(this._cvRouter.setInput(this._cameraEnhancer),e(this,ha,"m",Ea).call(this),yield e(this,ha,"m",Sa).call(this),this.disposed)))})},wa=function(n=!1){return t(this,void 0,void 0,function*(){if(n||(this.config.scanMode===a.SM_SINGLE?i(this,ma,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===a.SM_MULTI_UNIQUE&&i(this,ma,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const t=yield this._cvRouter.getSimplifiedSettings(e(this,ma,"f"));if(this.disposed)return;n||this.config.scanMode!==a.SM_SINGLE||(t.outputOriginalImage=!0);let r=this.config.barcodeFormats;if(r){Array.isArray(r)||(r=[r]),t.barcodeSettings.barcodeFormatIds=BigInt(0);for(let e=0;e{document.head.appendChild(t.cloneNode(!0))}),i(this,ga,v.querySelector(".result-item"),"f");const w=v.querySelector(".btn-clear");if(w&&(w.addEventListener("click",()=>{e(this,da,"f").barcodeResults=[],e(this,ha,"m",Oa).call(this)}),null===(s=null===(r=null===(n=this.config)||void 0===n?void 0:n.resultViewConfig)||void 0===r?void 0:r.toolbarButtonsConfig)||void 0===s?void 0:s.clear)){const t=this.config.resultViewConfig.toolbarButtonsConfig.clear;w.style.display=t.isHidden?"none":"flex",w.className=t.className?t.className:"btn-clear",w.innerText=t.label?t.label:"Clear",t.isHidden&&(v.querySelector(".toolbar-btns").style.justifyContent="center")}const C=v.querySelector(".btn-done");if(C&&(C.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(u=null===(c=null===(h=this.config)||void 0===h?void 0:h.resultViewConfig)||void 0===c?void 0:c.toolbarButtonsConfig)||void 0===u?void 0:u.done)){const t=this.config.resultViewConfig.toolbarButtonsConfig.done;C.style.display=t.isHidden?"none":"flex",C.className=t.className?t.className:"btn-done",C.innerText=t.label?t.label:"Done",t.isHidden&&(v.querySelector(".toolbar-btns").style.justifyContent="center")}if(null===(f=null===(d=this.config)||void 0===d?void 0:d.scannerViewConfig)||void 0===f?void 0:f.showCloseButton){const t=v.querySelector(".btn-close");t&&(t.style.display="",t.addEventListener("click",()=>{e(this,da,"f").barcodeResults=[],e(this,da,"f").status={code:l.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}if(null===(g=this.config)||void 0===g?void 0:g.scannerViewConfig.showFlashButton){const i=v.querySelector(".btn-flash-auto"),n=v.querySelector(".btn-flash-open"),r=v.querySelector(".btn-flash-close");if(i){i.style.display="";let s=null,o=250,a=20,h=3;const l=(l=250)=>t(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==s){if(!(lt(this,void 0,void 0,function*(){var t;if(e(this,fa,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(s),void(s=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(s),s=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(_.IPF_GRAYSCALED===l.format){for(let t=0;t=h){null===(t=Os._onLog)||void 0===t||t.call(Os,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,i.style.display="none",n.style.display="",r.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});s=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),i.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),i.style.display="none",n.style.display="",r.style.display="none"})),n.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),i.style.display="none",n.style.display="none",r.style.display=""})),r.addEventListener("click",()=>t(this,void 0,void 0,function*(){l(1e3),i.style.display="",n.style.display="none",r.style.display="none"}))}}let E=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(E)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const i=v.querySelector(".camera-control");if(i){i.style.display="";const n=yield this._cameraEnhancer.getAllCameras(),r=this.config.scannerViewConfig.cameraSwitchControl,s=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px"}),e},o=()=>{if(0===n.length)return null;if("listAll"===r){const i=v.querySelector(".camera-list");for(let t of n){const e=s(t);i.append(e)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const r=t=>{for(let e of o)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};i.addEventListener("click",i=>t(this,void 0,void 0,function*(){const t=i.target;e(this,ha,"m",La).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:t.deviceId,label:t.label,_checked:t._checked});const n=this._cameraEnhancer.getSelectedCamera(),s=this._cameraEnhancer.getCapabilities();uo(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(s.torch?e(this,ha,"m",Da).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),r(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,ma,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),e(this,ha,"m",La).call(this,"Loading...",!1)}));const o=v.querySelectorAll(".camera-list div");return()=>t(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();r(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===r?()=>t(this,void 0,void 0,function*(){e(this,ha,"m",La).call(this,"Accessing Camera...",!0);const t=uo(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&e(this,ha,"m",Da).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&e(this,ha,"m",Da).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),e(this,ha,"m",La).call(this,"Loading...",!1)}):void 0},a=o();i.addEventListener("click",e=>t(this,void 0,void 0,function*(){e.stopPropagation(),a&&(yield a())}))}}this.config.showUploadImageButton&&e(this,ha,"m",Aa).call(this,v.querySelector(".btn-upload-image"));const S=this._cameraView.getUIElement();S.shadowRoot.querySelector(".dce-sel-camera").remove(),S.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const b=v.querySelector(".barcode-scanner-container");b.style.display=ho()?"flex":"",this.config.scanMode===a.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===a.SM_SINGLE&&(this.config.showResultView=!1);const T=this.config.showResultView;let I;if(this.config.container?(b.style.position="relative",I=this.config.container):I=document.body,"string"==typeof I&&(I=document.querySelector(I),null===I))throw new Error("Failed to get the container");let x=this.config.scannerViewConfig.container;if("string"==typeof x&&(x=document.querySelector(x),null===x))throw new Error("Failed to get the container of the scanner view.");let O=this.config.resultViewConfig.container;if("string"==typeof O&&(O=document.querySelector(O),null===O))throw new Error("Failed to get the container of the result view.");const R=v.querySelector(".scanner-view-container"),A=v.querySelector(".result-view-container"),D=v.querySelector(".loading-page");R.append(D),x&&(R.append(S),x.append(R)),O&&O.append(A),x||O?x&&!O?(this.config.container||(A.style.position="absolute"),O=A,I.append(A)):!x&&O&&(this.config.container||(R.style.position="absolute"),x=R,R.append(S),I.append(R)):(x=R,O=A,T&&(Object.assign(R.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"}),Object.assign(A.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"})),R.append(S),I.append(b)),document.querySelector(".result-view-container").style.display=T?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),i(this,ua,()=>{Object.assign(b.style,{display:ho()?"flex":""}),!T||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(x.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"}),Object.assign(O.style,{width:ho()?"50%":"100%",height:ho()?"100%":"50%"}))},"f"),window.addEventListener("resize",e(this,ua,"f")),this._cameraView._createDrawingLayer(2)})},Ea=function(){const i=new Ge;i.onCapturedResultReceived=i=>t(this,void 0,void 0,function*(){if(e(this,pa,"f")&&e(this,pa,"f").clearDrawingItems(),i.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of i.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));e(this,pa,"f").addDrawingItems(t)}this.config.scanMode===a.SM_SINGLE?e(this,ha,"m",ba).call(this,i):e(this,ha,"m",Ta).call(this,i)}}),this._cvRouter.addResultReceiver(i)},Sa=function(){return t(this,void 0,void 0,function*(){e(this,_a,"f")||i(this,_a,new ia,"f"),e(this,_a,"f").enableResultCrossVerification(2,!0),e(this,_a,"f").enableResultDeduplication(2,!0),e(this,_a,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(e(this,_a,"f")),e(this,_a,"f").isResultCrossVerificationEnabled=()=>!1,e(this,_a,"f").isResultDeduplicationEnabled=()=>!1})},ba=function(t){const i=this._cameraView.getUIElement().shadowRoot;let n=new Promise(n=>{if(t.decodedBarcodesResult.barcodeResultItems.length>1){e(this,ha,"m",xa).call(this);for(let e of t.decodedBarcodesResult.barcodeResultItems){let t=0,r=0;for(let i=0;i<4;++i){let n=e.location.points[i];t+=n.x,r+=n.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:t/4,y:r/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer",transform:"translate(-50%, -50%)"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{n(e)}),i.append(o)}}else n(t.decodedBarcodesResult.barcodeResultItems[0])});n.then(i=>{const n=t.items.filter(t=>t.type===ft.CRIT_ORIGINAL_IMAGE)[0].imageData,r={status:{code:l.RS_SUCCESS,message:"Success."},originalImageResult:n,barcodeImage:(()=>{const t=W(n),e=i.location.points,r=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-r,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-r,e[0].y-s);for(let t=1;t`${t.formatString}_${t.text}`==`${i.formatString}_${i.text}`);-1===t?(i.count=1,e(this,da,"f").barcodeResults.unshift(i),e(this,ha,"m",Oa).call(this,i)):(e(this,da,"f").barcodeResults[t].count++,e(this,ha,"m",Ra).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},Ia=function(t){const i=e(this,ga,"f").cloneNode(!0);i.querySelector(".format-string").innerText=t.formatString;i.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),i.id=`${t.formatString}_${t.text}`;return i.querySelector(".delete-icon").addEventListener("click",()=>{const i=[...document.querySelectorAll(".main-list .result-item")],n=i.findIndex(e=>e.id===`${t.formatString}_${t.text}`);e(this,da,"f").barcodeResults.splice(n,1),i[n].remove(),0===e(this,da,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),i},xa=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0","background-color":"#4C4C4C",opacity:"0.5"}),t.append(e),this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Oa=function(t){if(!this.config.showResultView)return;const i=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==a.SM_SINGLE))return;const n=document.querySelector(".main-list");if(!t)return n.textContent="",void(this.config.showPoweredByDynamsoft&&(i.style.display=""));i.style.display="none";const r=e(this,ha,"m",Ia).call(this,t);n.insertBefore(r,document.querySelector(".result-item"))},Ra=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},Aa=function(i){i||(i=document.querySelector(".btn-upload-image")),i&&(i.style.display="",i.onchange=i=>t(this,void 0,void 0,function*(){const t=i.target.files,n={status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]};let r=0;e(this,ha,"m",La).call(this,`Capturing... [${r}/${t.length}]`,!0);let s=!1;for(let e=0;e`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===i?(t.count=1,e(this,da,"f").barcodeResults.unshift(t),e(this,ha,"m",Oa).call(this,t)):(e(this,da,"f").barcodeResults[i].count++,e(this,ha,"m",Ra).call(this,i))}else if(s.decodedBarcodesResult.barcodeResultItems)for(let t of s.decodedBarcodesResult.barcodeResultItems){const e=n.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,n.barcodeResults.push(t))}e(this,ha,"m",La).call(this,`Capturing... [${++r}/${t.length}]`,!0)}catch(t){n.status={code:l.RS_FAILED,message:t.message||t},e(Na,la,"f",ca).reject(new Error(n.status.message)),this.dispose()}e(this,ha,"m",La).call(this,"Loading...",!1),this.config.scanMode===a.SM_SINGLE&&(e(Na,la,"f",ca).resolve(n),this.dispose()),i.target.value=""}))},Da=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},La=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},Ma=function(t){let e=Ft();Pt[e]=()=>{},Lt.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},ca={value:null};const Ba="undefined"==typeof self,ja="function"==typeof importScripts,Ua=(()=>{if(!ja){if(!Ba&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Va=t=>{if(null==t&&(t="./"),Ba||ja);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Yt.engineResourcePaths.dbr={version:"11.0.60-dev-20250812165905",path:Ua,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const Ga="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,Ga)<0&&(Yt.engineResourcePaths.std={version:Ga,path:Va(Ua+`../../dynamsoft-capture-vision-std@${Ga}/dist/`),isInternal:!0});const Wa="3.0.10";(!Yt.engineResourcePaths.dip||"string"!=typeof Yt.engineResourcePaths.dip&&U(Yt.engineResourcePaths.dip.version,Wa)<0)&&(Yt.engineResourcePaths.dip={version:Wa,path:Va(Ua+`../../dynamsoft-image-processing@${Wa}/dist/`),isInternal:!0});let Ya=class{static getVersion(){const t=Ut.dbr&&Ut.dbr.wasm;return`11.0.60-dev-20250812165905(Worker: ${Ut.dbr&&Ut.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const Ha={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Xa,za,qa,Ka,Za,Ja;function $a(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Qa(e,t,"map"),t.getFieldRawValue=t=>Qa(e,t,"raw"),t.getFieldMappingStatus=t=>th(e,t),t.getFieldValidationStatus=t=>eh(e,t),delete t.fullCodeString}function Qa(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=Qa(r,e,i);if(void 0!==t)return t}}}function th(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Za[i.MappingStatus]):Za.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=th(n,e);if(void 0!==t)return t}}}function eh(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(Ja[i.ValidationStatus]):Ja.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=eh(n,e);if(void 0!==t)return t}}}function ih(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!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"}(Xa||(Xa={})),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"}(za||(za={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(qa||(qa={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(Ka||(Ka={})),function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(Za||(Za={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(Ja||(Ja={}));const nh=t=>t&&"object"==typeof t&&"function"==typeof t.then,rh=(async()=>{})().constructor;class sh extends rh{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,nh(t)?e=t:"function"==typeof t&&(e=new rh(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(nh(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class oh{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!Vt.license)throw Error("Module `license` is not existed.");await Vt.license.dynamsoft(),await Yt.loadWasm();const t=new oh,e=new sh;let i=Ft();return Pt[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},Lt.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){ih(this);let t=Ft();this.bDestroyed=!0,Pt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Lt.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(ih(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await B(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return ih(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(ih(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise((i,n)=>{let r=Ft();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):($a(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Lt.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const ah="undefined"==typeof self,hh="function"==typeof importScripts,lh=(()=>{if(!hh){if(!ah&&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"./"}})();Yt.engineResourcePaths.dcp={version:"3.0.60-dev-20250812165958",path:lh,isInternal:!0},Gt.dcp={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE]},Vt.dcp={handleParsedResultItem:$a};const ch="2.0.0";"string"!=typeof Yt.engineResourcePaths.std&&U(Yt.engineResourcePaths.std.version,ch)<0&&(Yt.engineResourcePaths.std={version:ch,path:(t=>{if(null==t&&(t="./"),ah||hh);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(lh+`../../dynamsoft-capture-vision-std@${ch}/dist/`),isInternal:!0});class uh{static getVersion(){const t=Ut.dcp&&Ut.dcp.wasm;return`3.0.60-dev-20250812165958(Worker: ${Ut.dcp&&Ut.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await Yt.loadWasm(),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],o=V(Yt.engineResourcePaths);Lt.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===Yt._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}}Yt._bundleEnv="DBR",Ve._defaultTemplate="ReadSingleBarcode",Yt.engineResourcePaths.rootDirectory=o(s+"../../"),Yt.engineResourcePaths.dbrBundle={version:"11.0.6000",path:s,isInternal:!0};export{Ya as BarcodeReaderModule,Na as BarcodeScanner,Os as CameraEnhancer,Qe as CameraEnhancerModule,Br as CameraManager,Pr as CameraView,Ve as CaptureVisionRouter,de as CaptureVisionRouterModule,Ge as CapturedResultReceiver,oh as CodeParser,uh as CodeParserModule,Yt as CoreModule,Oi as DrawingItem,Rr as DrawingStyleManager,Ha as EnumBarcodeFormat,m as EnumBufferOverflowProtectionMode,ft as EnumCapturedResultItemType,p as EnumColourChannelUsageType,gt as EnumCornerType,Ct as EnumCrossVerificationStatus,Ka as EnumDeblurMode,ci as EnumDrawingItemMediaType,ui as EnumDrawingItemState,di as EnumEnhancedFeatures,mt as EnumErrorCode,Xa as EnumExtendedBarcodeResultType,aa as EnumFilterType,pt as EnumGrayscaleEnhancementMode,_t as EnumGrayscaleTransformationMode,It as EnumImageCaptureDistanceMode,Tt as EnumImageFileFormat,_ as EnumImagePixelFormat,fe as EnumImageSourceState,vt as EnumImageTagType,Et as EnumIntermediateResultUnitType,qa as EnumLocalizationMode,Za as EnumMappingStatus,xt as EnumModuleName,h as EnumOptimizationMode,yt as EnumPDFReadingMode,Ye as EnumPresetTemplate,za as EnumQRCodeErrorCorrectionLevel,wt as EnumRasterDataSource,St as EnumRegionObjectElementType,l as EnumResultStatus,a as EnumScanMode,bt as EnumSectionType,Ot as EnumTransformMatrixType,Ja as EnumValidationStatus,Es as Feedback,Gi as GroupDrawingItem,kr as ImageDataGetter,Pa as ImageDrawer,Pi as ImageDrawingItem,Bs as ImageEditorView,Fa as ImageIO,ka as ImageProcessor,ht as ImageSourceAdapter,We as IntermediateResultReceiver,so as LicenseManager,ao as LicenseModule,Ui as LineDrawingItem,ia as MultiFrameResultCrossFilter,Vi as QuadDrawingItem,Ri as RectDrawingItem,Ni as TextDrawingItem,Co as UtilityModule,X as _getNorImageData,G as _saveToFile,H as _toBlob,W as _toCanvas,Y as _toImage,Bt as bDebug,j as checkIsLink,U as compareVersion,Dt as doOrWaitAsyncDependency,Ft as getNextTaskID,V as handleEngineResourcePaths,Ut as innerVersions,I as isArc,x as isContour,A as isDSImageData,D as isDSRect,L as isImageTag,M as isLineSegment,T as isObject,R as isOriginalDsImageData,F as isPoint,P as isPolygon,k as isQuad,N as isRect,z as isSimdSupported,Rt as mapAsyncDependency,Vt as mapPackageRegister,Pt as mapTaskCallBack,kt as onLog,q as productNameMap,B as requestResource,jt as setBDebug,Nt as setOnLog,At as waitAsyncDependency,Lt as worker,Gt as workerAutoResources}; +function t(t,e,i,n){return new(i||(i=Promise))(function(r,s){function o(t){try{h(n.next(t))}catch(t){s(t)}}function a(t){try{h(n.throw(t))}catch(t){s(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(o,a)}h((n=n.apply(t,e||[])).next())})}function e(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function i(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const n="undefined"==typeof self,r="function"==typeof importScripts,s=(()=>{if(!r){if(!n&&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"./"}})(),o=t=>{if(null==t&&(t="./"),n||r);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var a,h,l;!function(t){t[t.SM_SINGLE=0]="SM_SINGLE",t[t.SM_MULTI_UNIQUE=1]="SM_MULTI_UNIQUE"}(a||(a={})),function(t){t[t.OM_NONE=0]="OM_NONE",t[t.OM_SPEED=1]="OM_SPEED",t[t.OM_COVERAGE=2]="OM_COVERAGE",t[t.OM_BALANCE=3]="OM_BALANCE",t[t.OM_DPM=4]="OM_DPM",t[t.OM_DENSE=5]="OM_DENSE"}(h||(h={})),function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(l||(l={}));const c=t=>t&&"object"==typeof t&&"function"==typeof t.then,u=(async()=>{})().constructor;let d=class extends u{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,c(t)?e=t:"function"==typeof t&&(e=new u(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(c(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};function f(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function g(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}var m,p,_;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(m||(m={})),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"}(p||(p={})),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"}(_||(_={}));const v="undefined"==typeof self,y="function"==typeof importScripts,w=(()=>{if(!y){if(!v&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),C=t=>{if(null==t&&(t="./"),v||y);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},E=t=>Object.prototype.toString.call(t),S=t=>Array.isArray?Array.isArray(t):"[object Array]"===E(t),b=t=>"number"==typeof t&&!Number.isNaN(t),T=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),I=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.radius)||t.radius<0||!b(t.startAngle)||!b(t.endAngle)),x=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),O=t=>!(!T(t)||!b(t.width)||t.width<=0||!b(t.height)||t.height<=0||!b(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!L(t.tag)),R=t=>!(!O(t)||!b(t.bytes.length)&&!b(t.bytes.ptr)),A=t=>!!O(t)&&t.bytes instanceof Uint8Array,D=t=>!(!T(t)||!b(t.left)||t.left<0||!b(t.top)||t.top<0||!b(t.right)||t.right<0||!b(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom),L=t=>null===t||!!T(t)&&!!b(t.imageId)&&"type"in t,M=t=>!(!T(t)||!F(t.startPoint)||!F(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),F=t=>!!T(t)&&!!b(t.x)&&!!b(t.y),P=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&!t.points.some(t=>!F(t)),k=t=>!!T(t)&&!!S(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some(t=>!F(t)),N=t=>!(!T(t)||!b(t.x)||!b(t.y)||!b(t.width)||t.width<0||!b(t.height)||t.height<0),B=async(t,e,i)=>await new Promise((n,r)=>{let s=new XMLHttpRequest;s.responseType=e,s.onloadstart=()=>{i&&i.loadstartCallback&&i.loadstartCallback()},s.onloadend=async()=>{i&&i.loadendCallback&&i.loadendCallback(),s.status<200||s.status>=300?r(new Error(t+" "+s.status)):n(s.response)},s.onprogress=t=>{i&&i.progressCallback&&i.progressCallback(t)},s.onerror=()=>{r(new Error("Network Error: "+s.statusText))},s.open("GET",t,!0),s.send()}),j=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),U=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={};for(let i in t){if("rootDirectory"===i)continue;let n=i,r=t[n],s=r&&"object"==typeof r&&r.path?r.path:r,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof r&&r.isInternal)o&&(s=t[n].version?`${o}${q[n]}@${t[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${q[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(i,o||"")),"object"==typeof s&&"dwt"===n){const r=t[n].resourcesPath,s=t[n].serviceInstallerLocation;e[n]={resourcesPath:r.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[n]=C(s)}return e},G=async(t,e,i)=>await new Promise(async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const o=await H(`image/${s}`,t);r.length<=1&&(s="png");const a=new File([o],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(a),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(a)}catch(t){return r()}}),W=t=>{A(t)&&(t=X(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},Y=(t,e)=>{A(e)&&(e=X(e));const i=W(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},H=async(t,e)=>{A(e)&&(e=X(e));const i=W(e);return new Promise((e,n)=>{i.toBlob(t=>e(t),t)})},X=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===_.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=(128&n)/128*255,e[o+3]=255,n<<=1}}}else if(Number(t.format)===_.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[o]=e[o+1]=e[o+2]=128&n?0:255,e[o+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)},z=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),q={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcvData:"dynamsoft-capture-vision-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer",dwt:"dwt",dbrBundle:"dynamsoft-barcode-reader-bundle",dcvBundle:"dynamsoft-capture-vision-bundle"};var K,Z,J,$,Q,tt,et,it;let nt,rt,st,ot,at,ht=class t{get _isFetchingStarted(){return f(this,Q,"f")}constructor(){K.add(this),Z.set(this,[]),J.set(this,1),$.set(this,m.BOPM_BLOCK),Q.set(this,!1),tt.set(this,void 0),et.set(this,p.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!A(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(f(this,Z,"f").length>=f(this,J,"f"))switch(f(this,$,"f")){case m.BOPM_BLOCK:break;case m.BOPM_UPDATE:if(f(this,Z,"f").push(t),T(f(this,tt,"f"))&&b(f(this,tt,"f").imageId)&&1==f(this,tt,"f").keepInBuffer)for(;f(this,Z,"f").length>f(this,J,"f");){const t=f(this,Z,"f").findIndex(t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==f(this,tt,"f").imageId});f(this,Z,"f").splice(t,1)}else f(this,Z,"f").splice(0,f(this,Z,"f").length-f(this,J,"f"))}else f(this,Z,"f").push(t)}getImage(){if(0===f(this,Z,"f").length)return null;let e;if(f(this,tt,"f")&&b(f(this,tt,"f").imageId)){const t=f(this,K,"m",it).call(this,f(this,tt,"f").imageId);if(t<0)throw new Error(`Image with id ${f(this,tt,"f").imageId} doesn't exist.`);e=f(this,Z,"f").slice(t,t+1)[0]}else e=f(this,Z,"f").pop();if([_.IPF_RGB_565,_.IPF_RGB_555,_.IPF_RGB_888,_.IPF_ARGB_8888,_.IPF_RGB_161616,_.IPF_ARGB_16161616,_.IPF_ABGR_8888,_.IPF_ABGR_16161616,_.IPF_BGR_888].includes(e.format)){if(f(this,et,"f")===p.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every(t=>b(t)))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&"[object Boolean]"!==E(e))throw new TypeError("Invalid 'keepInBuffer'.");g(this,tt,{imageId:t,keepInBuffer:e},"f")}_resetNextReturnedImage(){g(this,tt,null,"f")}hasImage(t){return f(this,K,"m",it).call(this,t)>=0}startFetching(){g(this,Q,!0,"f")}stopFetching(){g(this,Q,!1,"f")}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(g(this,J,t,"f");f(this,Z,"f")&&f(this,Z,"f").length>t;)f(this,Z,"f").shift()}getMaxImageCount(){return f(this,J,"f")}getImageCount(){return f(this,Z,"f").length}clearBuffer(){f(this,Z,"f").length=0}isBufferEmpty(){return 0===f(this,Z,"f").length}setBufferOverflowProtectionMode(t){g(this,$,t,"f")}getBufferOverflowProtectionMode(){return f(this,$,"f")}setColourChannelUsageType(t){g(this,et,t,"f")}getColourChannelUsageType(){return f(this,et,"f")}};Z=new WeakMap,J=new WeakMap,$=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,K=new WeakSet,it=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return f(this,Z,"f").findIndex(e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t})},"undefined"!=typeof navigator&&(nt=navigator,rt=nt.userAgent,st=nt.platform,ot=nt.mediaDevices),function(){if(!v){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:nt.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:st,search:"Win"},Mac:{str:st},Linux:{str:st}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||rt,o=r.search||e,a=r.verStr||rt,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||rt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=rt.indexOf("Windows NT")&&(r="HarmonyOS"),at={browser:i,version:n,OS:r}}v&&(at={browser:"ssr",version:0,OS:"ssr"})}();const lt="undefined"!=typeof WebAssembly&&rt&&!(/Safari/.test(rt)&&!/Chrome/.test(rt)&&/\(.+\s11_2_([2-6]).*\)/.test(rt)),ct=!("undefined"==typeof Worker),ut=!(!ot||!ot.getUserMedia),dt=async()=>{let t=!1;if(ut)try{(await ot.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};var ft,gt,mt,pt,_t,vt,yt,wt,Ct;"Chrome"===at.browser&&at.version>66||"Safari"===at.browser&&at.version>13||"OPR"===at.browser&&at.version>43||"Edge"===at.browser&&at.version,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",t[t.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(ft||(ft={})),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"}(gt||(gt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",t[t.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",t[t.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",t[t.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",t[t.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",t[t.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(mt||(mt={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV",t[t.GEM_END=-1]="GEM_END"}(pt||(pt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV",t[t.GTM_END=-1]="GTM_END"}(_t||(_t={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(vt||(vt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(yt||(yt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(wt||(wt={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(Ct||(Ct={}));const Et={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var St,bt,Tt,It,xt,Ot;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",t[t.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(St||(St={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",t[t.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(bt||(bt={})),function(t){t[t.IFF_JPEG=0]="IFF_JPEG",t[t.IFF_PNG=1]="IFF_PNG",t[t.IFF_BMP=2]="IFF_BMP",t[t.IFF_PDF=3]="IFF_PDF"}(Tt||(Tt={})),function(t){t[t.ICDM_NEAR=0]="ICDM_NEAR",t[t.ICDM_FAR=1]="ICDM_FAR"}(It||(It={})),function(t){t.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",t.MN_DYNAMSOFT_CORE="core",t.MN_DYNAMSOFT_LICENSE="license",t.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",t.MN_DYNAMSOFT_UTILITY="utility",t.MN_DYNAMSOFT_BARCODE_READER="dbr",t.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",t.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",t.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",t.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",t.MN_DYNAMSOFT_CODE_PARSER="dcp",t.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",t.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(xt||(xt={})),function(t){t[t.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",t[t.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",t[t.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",t[t.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(Ot||(Ot={}));const Rt={},At=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push(Rt[t]=Rt[t]||new d);await Promise.all(i)},Dt=async(t,e)=>{let i,n="string"==typeof t?[t]:t,r=[];for(let t of n){let n;r.push(n=Rt[t]=Rt[t]||new d(i=i||e())),n.isEmpty&&(n.task=i=i||e())}await Promise.all(r)};let Lt,Mt=0;const Ft=()=>Mt++,Pt={};let kt;const Nt=t=>{kt=t,Lt&&Lt.postMessage({type:"setBLog",body:{value:!!t}})};let Bt=!1;const jt=t=>{Bt=t,Lt&&Lt.postMessage({type:"setBDebug",body:{value:!!t}})},Ut={},Vt={},Gt={dip:{wasm:!0}},Wt={std:{version:"2.0.0",path:C(w+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.2.20-dev-20251029130528",path:w,isInternal:!0}};let Yt=5;"undefined"!=typeof navigator&&(Yt=navigator.hardwareConcurrency?navigator.hardwareConcurrency-1:5),Pt[-3]=async t=>{Ht.onWasmLoadProgressChanged&&Ht.onWasmLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class Ht{static get engineResourcePaths(){return Wt}static set engineResourcePaths(t){Object.assign(Wt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return kt}static set _onLog(t){Nt(t)}static get _bDebug(){return Bt}static set _bDebug(t){jt(t)}static get _workerName(){return`${Ht._bundleEnv.toLowerCase()}.bundle.worker.js`}static get wasmLoadOptions(){return Ht._wasmLoadOptions}static set wasmLoadOptions(t){Object.assign(Ht._wasmLoadOptions,t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!Rt[t]&&Rt[t].isFulfilled}static async loadWasm(){return await(async()=>{let t,e;t instanceof Array||(t=t?[t]:[]);let i=Rt.core;e=!i||i.isEmpty,e||await At("core");let n=new Map;const r=t=>{if(t=t.toLowerCase(),xt.MN_DYNAMSOFT_CAPTURE_VISION_STD==t||xt.MN_DYNAMSOFT_CORE==t)return;let e=Gt[t].deps;if(null==e?void 0:e.length)for(let t of e)r(t);let i=Rt[t];n.has(t)||n.set(t,!i||i.isEmpty)};for(let e of t)r(e);let s=[];e&&s.push("core"),s.push(...n.keys());const o=[...n.entries()].filter(t=>!t[1]).map(t=>t[0]);await Dt(s,async()=>{const t=[...n.entries()].filter(t=>t[1]).map(t=>t[0]);await At(o);const i=V(Wt),r={};for(let e of t)r[e]=Gt[e];const s={engineResourcePaths:i,autoResources:r,names:t,_bundleEnv:Ht._bundleEnv,wasmLoadOptions:Ht.wasmLoadOptions};let a=new d;if(e){s.needLoadCore=!0;let t=i[`${Ht._bundleEnv.toLowerCase()}Bundle`]+Ht._workerName;t.startsWith(location.origin)||(t=await fetch(t).then(t=>t.blob()).then(t=>URL.createObjectURL(t))),Lt=new Worker(t),Lt.onerror=t=>{let e=new Error(t.message);a.reject(e)},Lt.addEventListener("message",t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":kt&&kt(e.message);break;case"warning":console.warn(e.message);break;case"task":try{Pt[n](r),delete Pt[n]}catch(t){throw delete Pt[n],t}break;case"event":try{Pt[n](r)}catch(t){throw t}break;default:console.log(t)}}),s.bLog=!!kt,s.bd=Bt,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await At("core");let h=Mt++;Pt[h]=t=>{if(t.success)Object.assign(Ut,t.versions),"{}"!==JSON.stringify(t.versions)&&(Ht._versions=t.versions),Ht.loadedWasmType=t.loadedWasmType,a.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),a.reject(e)}},Lt.postMessage({type:"loadWasm",id:h,body:s}),await a})})()}static async detectEnvironment(){return await(async()=>({wasm:lt,worker:ct,getUserMedia:ut,camera:await dt(),browser:at.browser,version:at.version,OS:at.OS}))()}static async getModuleVersion(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"getModuleVersion",id:i})})}static getVersion(){return`4.2.20-dev-20251029130528(Worker: ${Ut.core&&Ut.core.worker||"Not Loaded"}, Wasm: ${Ut.core&&Ut.core.wasm||"Not Loaded"})`}static enableLogging(){ht._onLog=console.log,Ht._onLog=console.log}static disableLogging(){ht._onLog=null,Ht._onLog=null}static async cfd(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cfd",id:n,body:{count:t}})})}}Ht._bSupportDce4Module=-1,Ht._bSupportIRTModule=-1,Ht._versions=null,Ht._bundleEnv="DCV",Ht._wasmLoadOptions={wasmType:"auto",pthreadPoolSize:Yt},Ht.loadedWasmType="ml-simd-pthread",Ht.browserInfo=at;var Xt={license:"",scanMode:a.SM_SINGLE,templateFilePath:void 0,utilizedTemplateNames:{single:"ReadBarcodes_SpeedFirst",multi_unique:"ReadBarcodes_SpeedFirst",image:"ReadBarcodes_ReadRateFirst"},engineResourcePaths:Ht.engineResourcePaths,barcodeFormats:void 0,duplicateForgetTime:3e3,container:void 0,onUniqueBarcodeScanned:void 0,showResultView:void 0,showUploadImageButton:!1,showPoweredByDynamsoft:!0,autoStartCapturing:!0,uiPath:s,onInitPrepare:void 0,onInitReady:void 0,onCameraOpen:void 0,onCaptureStart:void 0,scannerViewConfig:{container:void 0,showCloseButton:!0,mirrorFrontCamera:!0,cameraSwitchControl:"hidden",showFlashButton:!1},resultViewConfig:{container:void 0,toolbarButtonsConfig:{clear:{label:"Clear",className:"btn-clear",isHidden:!1},done:{label:"Done",className:"btn-done",isHidden:!1}}}};const zt=t=>t&&"object"==typeof t&&"function"==typeof t.then,qt=(async()=>{})().constructor;class Kt extends qt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,zt(t)?e=t:"function"==typeof t&&(e=new qt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(zt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}function Zt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Jt(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const $t=t=>t&&"object"==typeof t&&"function"==typeof t.then,Qt=(async()=>{})().constructor;let te=class extends Qt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,$t(t)?e=t:"function"==typeof t&&(e=new Qt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&($t(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},ee=class{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})})}async setMaxBufferedItems(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})})}async getBufferedCharacterItemSet(){return await new Promise((t,e)=>{let i=Ft();Pt[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)}},Lt.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})})}};var ie={onTaskResultsReceived:!1,onTargetROIResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onDeskewedImageReceived:!1,onEnhancedImageReceived:!1,onColourImageUnitReceived:!1,onScaledColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesUnitReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesUnitReceived:!1};const ne=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};let re=class{constructor(t){this._irrRegistryState=ie,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),ne(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach((t,e)=>{i[e]=t}),t._observedTaskMap.clear()}return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})})}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),ne(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})})}getOriginalImage(){return this._cvr._dsImage}};const se="undefined"==typeof self,oe="function"==typeof importScripts,ae=(()=>{if(!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"./"}})(),he=t=>{if(null==t&&(t="./"),se||oe);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var le;Ht.engineResourcePaths.cvr={version:"3.2.20-dev-20251030140710",path:ae,isInternal:!0},Gt.cvr={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING,xt.MN_DYNAMSOFT_NEURAL_NETWORK]},Gt.dnn={wasm:!0,deps:[xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.cvr={};const ce="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,ce)<0&&(Ht.engineResourcePaths.std={version:ce,path:he(ae+`../../dynamsoft-capture-vision-std@${ce}/dist/`),isInternal:!0});const ue="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,ue)<0)&&(Ht.engineResourcePaths.dip={version:ue,path:he(ae+`../../dynamsoft-image-processing@${ue}/dist/`),isInternal:!0});const de="2.0.10";(!Ht.engineResourcePaths.dnn||"string"!=typeof Ht.engineResourcePaths.dnn&&U(Ht.engineResourcePaths.dnn.version,de)<0)&&(Ht.engineResourcePaths.dnn={version:de,path:he(ae+`../../dynamsoft-capture-vision-dnn@${de}/dist/`),isInternal:!0});let fe=class{static getVersion(){return this._version}};var ge,me,pe,_e,ve,ye,we,Ce,Ee,Se,be,Te,Ie,xe,Oe,Re,Ae,De,Le,Me,Fe,Pe,ke,Ne;function Be(t,e){if(t){if(t.sourceLocation){const i=t.sourceLocation.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}if(t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e}Be(t.referencedItem,e)}}function je(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}function Ue(t){return{type:ft.CRIT_ORIGINAL_IMAGE,referenceItem:null,targetROIDefName:"",taskName:"",imageData:t,toCanvas:()=>W(t),toImage:e=>Y(e,t),toBlob:e=>H(e,t)}}function Ve(t){let e=!1;const i=[mt.EC_UNSUPPORTED_JSON_KEY_WARNING,mt.EC_LICENSE_AUTH_QUOTA_EXCEEDED,mt.EC_LICENSE_RESULTS_LIMIT_EXCEEDED];if(t.errorCode&&i.includes(t.errorCode))return void console.warn(t.message);let n=new Error(t.errorCode?`[${t.functionName}] [${t.errorCode}] ${t.message}`:`[${t.functionName}] ${t.message}`);if(n.stack&&(n.stack=t.stack),t.isShouleThrow)throw n;return t.rj&&t.rj(n),e=!0,true}fe._version=`3.2.20-dev-20251030140710(Worker: ${null===(le=Ut.cvr)||void 0===le?void 0:le.worker}, Wasm: loading...`,function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ge||(ge={}));const Ge={onTaskResultsReceived:()=>{},isFilter:!0};Pt[-2]=async t=>{We.onDataLoadProgressChanged&&We.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};let We=class t{constructor(){me.add(this),this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(Ht.browserInfo.OS)?2048:4096,this.onCaptureError=null,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,this._dynamsoft=!0,pe.set(this,null),_e.set(this,null),ve.set(this,null),ye.set(this,null),we.set(this,null),Ce.set(this,new Set),Ee.set(this,new Set),Se.set(this,new Set),be.set(this,500),Te.set(this,0),Ie.set(this,0),xe.set(this,!1),Oe.set(this,!1),Re.set(this,!1),Ae.set(this,null),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Zt(this,Re,"f")}static async createInstance(e=!0){if(!Vt.license)throw Error("The `license` module cannot be found.");await Vt.license.dynamsoft(),await Ht.loadWasm();const i=new t,n=new te;let r=Ft();return Pt[r]=async e=>{e.success?(i._instanceID=e.instanceID,i._currentSettings=JSON.parse(JSON.parse(e.outputSettings).data),t._isNoOnnx=e.isNoOnnx,fe._version=`3.2.20-dev-20251030140710(Worker: ${Ut.cvr.worker}, Wasm: ${e.version})`,Jt(i,Oe,!0,"f"),Jt(i,ye,i.getIntermediateResultManager(),"f"),Jt(i,Oe,!1,"f"),n.resolve(i)):Ve({message:e.message,rj:n.reject,stack:e.stack,functionName:"createInstance"})},Lt.postMessage({type:"cvr_createInstance",id:r,body:{loadPresetTemplates:e,itemCountRecord:localStorage.getItem("dynamsoft")}}),n}static async appendDLModelBuffer(e,i){return await Ht.loadWasm(),t._isNoOnnx?Promise.reject("Model not supported in the current environment."):await new Promise((t,n)=>{let r=Ft();const s=V(Ht.engineResourcePaths);let o;Pt[r]=async e=>{if(e.success){const i=JSON.parse(e.response);return 0!==i.errorCode&&Ve({message:i.errorString?i.errorString:"Append Model Buffer Failed.",rj:n,errorCode:i.errorCode,functionName:"appendDLModelBuffer"}),t(i)}Ve({message:e.message,rj:n,stack:e.stack,functionName:"appendDLModelBuffer"})},i?o=i:"DCV"===Ht._bundleEnv?o=s.dcvData+"models/":"DBR"===Ht._bundleEnv&&(o=s.dbrBundle+"models/"),Lt.postMessage({type:"cvr_appendDLModelBuffer",id:r,body:{modelName:e,path:o}})})}static async clearDLModelBuffers(){return await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();Ve({message:i.message,rj:e,stack:i.stack,functionName:"clearDLModelBuffers"})},Lt.postMessage({type:"cvr_clearDLModelBuffers",id:i})})}async _singleFrameModeCallback(t){for(let e of Zt(this,Ce,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived(Ue(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,Zt(this,pe,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1}),Zt(this,me,"m",Me).call(this,i)}setInput(t){if(je(this),!t)return Zt(this,Ae,"f")&&(Zt(this,ye,"f").removeResultReceiver(Zt(this,Ae,"f")),Jt(this,Ae,null,"f")),void Jt(this,pe,null,"f");Jt(this,pe,t,"f"),t.isCameraEnhancer&&Zt(this,ye,"f")&&(Zt(this,pe,"f")._intermediateResultReceiver.isDce=!0,Zt(this,ye,"f").addResultReceiver(Zt(this,pe,"f")._intermediateResultReceiver),Jt(this,Ae,Zt(this,pe,"f")._intermediateResultReceiver,"f"))}getInput(){return Zt(this,pe,"f")}addImageSourceStateListener(t){if(je(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Zt(this,Ee,"f").add(t)}removeImageSourceStateListener(t){return je(this),Zt(this,Ee,"f").delete(t)}addResultReceiver(t){if(je(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Zt(this,Ce,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){je(this),Zt(this,Ce,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onProcessedDocumentResultReceived:!1,onParsedResultsReceived:!1};for(let e of Zt(this,Ce,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onProcessedDocumentResultReceived=!!e.onProcessedDocumentResultReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new te;let i=Ft();return Pt[i]=async t=>{t.success?e.resolve():Ve({message:t.message,rj:e.reject,stack:t.stack,functionName:"addResultReceiver"})},Lt.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(je(this),!t._dynamsoft)throw new Error("User defined CapturedResultFilter is not supported.");if(!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Zt(this,Se,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){je(this),Zt(this,Se,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Zt(this,ye,"f").removeResultReceiver(Ge),0===Zt(this,Se,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1},e={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1};return await Zt(this,me,"m",Fe).call(this,t),void await Zt(this,me,"m",Pe).call(this,e)}for(let t of Zt(this,Se,"f"))this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(ft.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(ft.CRIT_DESKEWED_IMAGE),t.isLatestOverlappingEnabled(ft.CRIT_BARCODE)&&([...Zt(this,ye,"f")._intermediateResultReceiverSet.values()].find(t=>t.isFilter)||Zt(this,ye,"f").addResultReceiver(Ge)),await Zt(this,me,"m",Fe).call(this,t.verificationEnabled),await Zt(this,me,"m",Pe).call(this,t.duplicateFilterEnabled),await Zt(this,me,"m",ke).call(this,t.duplicateForgetTime)}async startCapturing(e){if(je(this),!this._isPauseScan)return;if(!Zt(this,pe,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");e||(e=t._defaultTemplate);for(let t of Zt(this,Se,"f"))await this.addResultFilter(t);const i=V(Ht.engineResourcePaths);return void 0!==Zt(this,pe,"f").singleFrameMode&&"disabled"!==Zt(this,pe,"f").singleFrameMode?(this._templateName=e,void Zt(this,pe,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind)):Zt(this,ve,"f")&&Zt(this,ve,"f").isPending?Zt(this,ve,"f"):(Jt(this,ve,new te((t,n)=>{if(this.disposed)return;let r=Ft();Pt[r]=async i=>{Zt(this,ve,"f")&&!Zt(this,ve,"f").isFulfilled&&(i.success?(this._isPauseScan=!1,this._isOutputOriginalImage=i.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(async()=>{-1!==this._minImageCaptureInterval&&Zt(this,pe,"f").startFetching(),this._loopReadVideo(e),t()},0)):Ve({message:i.message,rj:n,stack:i.stack,functionName:"startCapturing"}))},Lt.postMessage({type:"cvr_startCapturing",id:r,instanceID:this._instanceID,body:{templateName:e,engineResourcePaths:i}})}),"f"),await Zt(this,ve,"f"))}stopCapturing(){je(this),Zt(this,pe,"f")&&(Zt(this,pe,"f").isCameraEnhancer&&void 0!==Zt(this,pe,"f").singleFrameMode&&"disabled"!==Zt(this,pe,"f").singleFrameMode?Zt(this,pe,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(Zt(this,me,"m",Ne).call(this),Zt(this,pe,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,Jt(this,ve,null,"f"),Zt(this,pe,"f").setColourChannelUsageType(p.CCUT_AUTO)))}async containsTask(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));Ve({message:t.message,rj:i,stack:t.stack,functionName:"containsTask"})},Lt.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async switchCapturingTemplate(t){this.stopCapturing(),await this.startCapturing(t)}async _loopReadVideo(e){if(this.disposed||this._isPauseScan)return;if(Jt(this,xe,!0,"f"),Zt(this,pe,"f").isBufferEmpty())if(Zt(this,pe,"f").hasNextImageToFetch())for(let t of Zt(this,Ee,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ge.ISS_BUFFER_EMPTY);else if(!Zt(this,pe,"f").hasNextImageToFetch())for(let t of Zt(this,Ee,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ge.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Zt(this,pe,"f").isBufferEmpty()&&Zt(this,pe,"f").isCameraEnhancer)try{Zt(this,pe,"f").isBufferEmpty()&&t._onLog&&t._onLog("buffer is empty so fetch image"),t._onLog&&t._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Zt(this,pe,"f").fetchImage(),t._onLog&&t._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Zt(this,pe,"f").setImageFetchInterval(this._averageTime)}catch(i){return void this._reRunCurrnetFunc(e)}else if(Zt(this,pe,"f").isCameraEnhancer&&Zt(this,pe,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Zt(this,pe,"f").getImage(),this._dsImage&&this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(e);if(!this._dsImage)return void this._reRunCurrnetFunc(e);for(let t of Zt(this,Ce,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived(Ue(this._dsImage));const i=Date.now();this._captureDsimage(this._dsImage,e).then(async n=>{if(t._onLog&&t._onLog("no js handle time: "+(Date.now()-i)),this._isPauseScan)return void this._reRunCurrnetFunc(e);n.originalImageTag=this._dsImage.tag?this._dsImage.tag:null,Zt(this,pe,"f").isCameraEnhancer&&Zt(this,pe,"f").cameraView._capturedResultReceiver.onCapturedResultReceived(n,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify});for(let t of Zt(this,Se,"f")){const e=t;e.onOriginalImageResultReceived(n),e.onDecodedBarcodesReceived(n),e.onRecognizedTextLinesReceived(n),e.onProcessedDocumentResultReceived(n),e.onParsedResultsReceived(n)}Zt(this,me,"m",Me).call(this,n);const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-i),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,t._onLog&&(t._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),t._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),t._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),t._onLog(`averageTime: ${this._averageTime}`))),t._onLog){const e=Date.now()-r;e>10&&t._onLog(`fetch image calculate time: ${e}`)}t._onLog&&t._onLog(`time finish decode: ${Date.now()}`),t._onLog&&t._onLog("main time: "+(Date.now()-i)),t._onLog&&t._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,0))}).catch(t=>{Zt(this,pe,"f").stopFetching(),"platform error"!==t.message&&(t.errorCode&&0===t.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{Zt(this,pe,"f").startFetching(),this._loopReadVideo(e)},Math.max(this._minImageCaptureInterval,1e3))),setTimeout(()=>{if(!this.onCaptureError)throw t;this.onCaptureError(t)},0))})}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout(()=>{this._loopReadVideo(t)},0)}async getClarity(t,e,i,n,r){const{bytes:s,width:o,height:a,stride:h,format:l}=t;let c=Ft();return new Promise((t,u)=>{Pt[c]=async e=>{e.success?t(e.clarity):Ve({message:e.message,rj:u,stack:e.stack,functionName:"getClarity"})},Lt.postMessage({type:"cvr_getClarity",id:c,instanceID:this._instanceID,body:{bytes:s,width:o,height:a,stride:h,format:l,bitcount:e,wr:i,hr:n,grayThreshold:r}},[s.buffer])})}async capture(e,i){let n;if(je(this),i||(i=t._defaultTemplate),Jt(this,xe,!1,"f"),A(e))n=await this._captureDsimage(e,i);else if("string"==typeof e)n="data:image/"==e.substring(0,11)?await this._captureBase64(e,i):await this._captureUrl(e,i);else if(e instanceof Blob)n=await this._captureBlob(e,i);else if(e instanceof HTMLImageElement)n=await this._captureImage(e,i);else if(e instanceof HTMLCanvasElement)n=await this._captureCanvas(e,i);else{if(!(e instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");n=await this._captureVideo(e,i)}return n}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await B(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(e){return await new Promise((i,n)=>{let r=URL.createObjectURL(e),s=new Image;s.src=r,s.onload=()=>{URL.revokeObjectURL(s.dbrObjUrl),i(s)},s.onerror=()=>{let e="Unsupported image format. Please upload files in one of the following formats: .jpg,.jpeg,.ico,.gif,.svg,.webp,.png,.bmp";"image/svg+xml"===t.type&&(e="Invalid SVG file. The file appears to be malformed or contains invalid XML."),n(new Error(e))}})}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(r,s);o>this.maxImageSideLength?(Jt(this,Ie,this.maxImageSideLength/o,"f"),i=Math.round(r*Zt(this,Ie,"f")),n=Math.round(s*Zt(this,Ie,"f"))):(i=r,n=s),Zt(this,_e,"f")||Jt(this,_e,document.createElement("canvas"),"f");const a=Zt(this,_e,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(a,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,o=Math.max(r,s);o>this.maxImageSideLength?(Jt(this,Ie,this.maxImageSideLength/o,"f"),i=Math.round(r*Zt(this,Ie,"f")),n=Math.round(s*Zt(this,Ie,"f"))):(i=r,n=s),Zt(this,_e,"f")||Jt(this,_e,document.createElement("canvas"),"f");const a=Zt(this,_e,"f");return a.width===i&&a.height===n||(a.width=i,a.height=n),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0})),a.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(a,e)}async _captureInWorker(e,i){const{bytes:n,width:r,height:s,stride:o,format:a}=e;let h=Ft();const l=new te;return Pt[h]=async i=>{if(i.success){const n=Date.now();t._onLog&&(t._onLog(`get result time from worker: ${n}`),t._onLog("worker to main time consume: "+(n-i.workerReturnMsgTime)));try{const t=i.captureResult;e.bytes=i.bytes,Zt(this,me,"m",De).call(this,t,e),i.isScanner||Jt(this,Ie,0,"f"),Zt(this,me,"m",Le).call(this,t,e);const n=Date.now();return n-Zt(this,Te,"f")>Zt(this,be,"f")&&(localStorage.setItem("dynamoft",JSON.stringify(i.itemCountRecord)),Jt(this,Te,n,"f")),l.resolve(t)}catch(i){Ve({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})}}else Ve({message:i.message,rj:l.reject,stack:i.stack,functionName:"capture"})},t._onLog&&t._onLog(`send buffer to worker: ${Date.now()}`),Lt.postMessage({type:"cvr_capture",id:h,instanceID:this._instanceID,body:{bytes:n,width:r,height:s,stride:o,format:a,templateName:i||"",isScanner:Zt(this,xe,"f"),dynamsoft:this._dynamsoft}},[n.buffer]),l}async initSettings(e){if(je(this),e&&["string","object"].includes(typeof e))return"string"==typeof e?e.trimStart().startsWith("{")||(e=await B(e,"text")):"object"==typeof e&&(e=JSON.stringify(e)),await new Promise((i,n)=>{let r=Ft();Pt[r]=async r=>{if(r.success){const s=JSON.parse(r.response);if(0!==s.errorCode&&Ve({message:s.errorString?s.errorString:"Init Settings Failed.",rj:n,errorCode:s.errorCode,functionName:"initSettings"}))return;const o=JSON.parse(e);return this._currentSettings=o,this._isOutputOriginalImage=1===this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage,t._defaultTemplate=this._currentSettings.CaptureVisionTemplates[0].Name,i(s)}Ve({message:r.message,rj:n,stack:r.stack,functionName:"initSettings"})},Lt.postMessage({type:"cvr_initSettings",id:r,instanceID:this._instanceID,body:{settings:e}})});console.error("Invalid template.")}async outputSettings(t,e){return je(this),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const e=JSON.parse(t.response);return 0!==e.errorCode&&Ve({message:e.errorString,rj:n,errorCode:e.errorCode,functionName:"outputSettings"}),i(JSON.parse(e.data))}Ve({message:t.message,rj:n,stack:t.stack,functionName:"outputSettings"})},Lt.postMessage({type:"cvr_outputSettings",id:r,instanceID:this._instanceID,body:{templateName:t||"*",includeDefaultValues:!!e}})})}async outputSettingsToFile(t,e,i,n){const r=await this.outputSettings(t,n),s=new Blob([JSON.stringify(r,null,2,function(t,e){return e instanceof Array?JSON.stringify(e):e},2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(s),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout(()=>{URL.revokeObjectURL(t.href)},500)},t.click()}return s}async getTemplateNames(){return je(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Ve({message:n.errorString,rj:e,errorCode:n.errorCode,functionName:"getTemplateNames"}),t(JSON.parse(n.data))}Ve({message:i.message,rj:e,stack:i.stack,functionName:"getTemplateNames"})},Lt.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})})}async getSimplifiedSettings(t){return je(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);0!==n.errorCode&&Ve({message:n.errorString,rj:i,errorCode:n.errorCode,functionName:"getSimplifiedSettings"});const r=JSON.parse(n.data,(t,e)=>"barcodeFormatIds"===t?BigInt(e):e);return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}Ve({message:t.message,rj:i,stack:t.stack,functionName:"getSimplifiedSettings"})},Lt.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async updateSettings(t,e){return je(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);return e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode&&Ve({message:r.errorString?r.errorString:"Update Settings Failed.",rj:n,errorCode:r.errorCode,functionName:"updateSettings"}),this._currentSettings=await this.outputSettings("*"),i(r)}Ve({message:t.message,rj:n,stack:t.stack,functionName:"updateSettings"})},Lt.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})})}async resetSettings(){return je(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);return 0!==n.errorCode&&Ve({message:n.errorString?n.errorString:"Reset Settings Failed.",rj:e,errorCode:n.errorCode,functionName:"resetSettings"}),this._currentSettings=await this.outputSettings("*"),t(n)}Ve({message:i.message,rj:e,stack:i.stack,functionName:"resetSettings"})},Lt.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})})}getBufferedItemsManager(){return Zt(this,we,"f")||Jt(this,we,new ee(this),"f"),Zt(this,we,"f")}getIntermediateResultManager(){if(je(this),!Zt(this,Oe,"f")&&0!==Ht.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Zt(this,ye,"f")||Jt(this,ye,new re(this),"f"),Zt(this,ye,"f")}static async setGlobalIntraOpNumThreads(t=0){return t>4||t<0?Promise.reject(new RangeError("'intraOpNumThreads' should be between 0 and 4.")):(await Ht.loadWasm(),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e();Ve({message:t.message,rj:i,stack:t.stack,functionName:"setGlobalIntraOpNumThreads"})},Lt.postMessage({type:"cvr_setGlobalIntraOpNumThreads",id:n,body:{intraOpNumThreads:t}})}))}async parseRequiredResources(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));Ve({message:t.message,rj:i,stack:t.stack,functionName:"parseRequiredResources"})},Lt.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})})}async dispose(){je(this),Zt(this,ve,"f")&&this.stopCapturing(),Jt(this,pe,null,"f"),Zt(this,Ce,"f").clear(),Zt(this,Ee,"f").clear(),Zt(this,Se,"f").clear(),Zt(this,ye,"f")._intermediateResultReceiverSet.clear(),Jt(this,Re,!0,"f");let t=Ft();Pt[t]=t=>{t.success||Ve({message:t.message,stack:t.stack,isShouleThrow:!0,functionName:"dispose"})},Lt.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Zt(this,pe,"f"),promiseStartScan:Zt(this,ve,"f"),intermediateResultManager:Zt(this,ye,"f"),bufferdItemsManager:Zt(this,we,"f"),resultReceiverSet:Zt(this,Ce,"f"),isaStateListenerSet:Zt(this,Ee,"f"),resultFilterSet:Zt(this,Se,"f"),compressRate:Zt(this,Ie,"f"),canvas:Zt(this,_e,"f"),isScanner:Zt(this,xe,"f"),innerUseTag:Zt(this,Oe,"f"),isDestroyed:Zt(this,Re,"f")}}async _getWasmFilterState(){return await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}Ve({message:i.message,rj:e,stack:i.stack,functionName:""})},Lt.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})})}};pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Re=new WeakMap,Ae=new WeakMap,me=new WeakSet,De=function(t,e){var i,n,r,s,o,a,h,l,c,u,d,f;for(let g=0;g{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);Ve({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultCrossVerification",id:n,instanceID:this._instanceID,body:{verificationEnabled:t}})})},Pe=async function(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);Ve({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_enableResultDeduplication",id:n,instanceID:this._instanceID,body:{duplicateFilterEnabled:t}})})},ke=async function(t){return je(this),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return e(t.result);Ve({message:t.message,rj:i,stack:t.stack,functionName:"addResultFilter"})},Lt.postMessage({type:"cvr_setDuplicateForgetTime",id:n,instanceID:this._instanceID,body:{duplicateForgetTime:t}})})},Ne=async function(){let t=Ft();const e=new te;return Pt[t]=async t=>{if(t.success)return e.resolve();Ve({message:t.message,rj:e.reject,stack:t.stack,functionName:"stopCapturing"})},Lt.postMessage({type:"cvr_clearVerifyList",id:t,instanceID:this._instanceID}),e},We._defaultTemplate="Default",We._isNoOnnx=!1;let Ye=class{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}},He=class{constructor(){this._observedResultUnitTypes=Et.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}};var Xe;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadSingleBarcode",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Xe||(Xe={}));const ze="undefined"==typeof self,qe="function"==typeof importScripts,Ke=(()=>{if(!qe){if(!ze&&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"./"}})();Ht.engineResourcePaths.dce={version:"4.3.3-dev-20251029130621",path:Ke,isInternal:!0},Gt.dce={wasm:!1,js:!1},Vt.dce={};let Ze,Je,$e,Qe,ti,ei=class{static getVersion(){return"4.3.3-dev-20251029130621"}};function ii(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ni(t,e,i,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(t,i):r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ze=navigator,Je=Ze.userAgent,$e=Ze.platform,Qe=Ze.mediaDevices),function(){if(!ze){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ze.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:$e,search:"Win"},Mac:{str:$e},Linux:{str:$e}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Je,o=r.search||e,a=r.verStr||Je,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Je,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Je.indexOf("Windows NT")&&(r="HarmonyOS"),ti={browser:i,version:n,OS:r}}ze&&(ti={browser:"ssr",version:0,OS:"ssr"})}();const ri="undefined"!=typeof WebAssembly&&Je&&!(/Safari/.test(Je)&&!/Chrome/.test(Je)&&/\(.+\s11_2_([2-6]).*\)/.test(Je)),si=!("undefined"==typeof Worker),oi=!(!Qe||!Qe.getUserMedia),ai=async()=>{let t=!1;if(oi)try{(await Qe.getUserMedia({video:!0})).getTracks().forEach(t=>{t.stop()}),t=!0}catch(t){}return t};"Chrome"===ti.browser&&ti.version>66||"Safari"===ti.browser&&ti.version>13||"OPR"===ti.browser&&ti.version>43||"Edge"===ti.browser&&ti.version;var hi={653:(t,e,i)=>{var n,r,s,o,a,h,l,c,u,d,f,g,m,p,_,v,y,w,C,E,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,n,r);i.putImageData(h,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some(function(e){return"function"==typeof e.contains&&e.contains(t,!0)})},complexity:function(){return this._objects.reduce(function(t,e){return t+(e.complexity?e.complexity():0)},0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),o=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,o)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),o=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach(function(a,h){var l,c,u=new b.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(b.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(b.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=b.util.getBisector(u,l,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new b.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new b.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))}),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,o=t.getImageData(e,i,2*n||1,2*n||1),a=o.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=b.util.sin(c),d=b.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(o===a?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,I=-E*s*m/i,x=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=r(1,0,(m-T)/i,(p-I)/s),A=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),L=[],M=A/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=R+M,k=0;kE)for(var T=1,I=m.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,h=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+a*e,r.y+h*e]),n},b.util.getPathSegmentsInfo=d,b.util.getBoundsOfCurve=function(e,i,n,r,s,o,a,h){var l;if(b.cachesBoundsOfCurve&&(l=t.call(arguments),b.boundsOfCurveCache[l]))return b.boundsOfCurveCache[l];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*a,d=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*r+6*o,c=-3*i+9*r-9*o+3*h,d=3*r-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&E.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-u-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,R=E.length,A=R;R--;)I=(O=1-(f=E[R]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*a,S[0][R]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*o+f*f*f*h,S[1][R]=x;S[0][A]=e,S[1][A]=i,S[0][A+1]=a,S[1][A+1]=h;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[l]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=h(s),r=s,(n=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=n);return i.angle=u(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(function(t){for(var i=t.slice(0),n={},r=1;r=e})}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(r.prototype=i.prototype,a.prototype=new r,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=b.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function a(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=o,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=a,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=a(t),{left:s.left+n.left-(i.clientLeft||0)+o.left,top:s.top+n.top-(i.clientTop||0)+o.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach(function(t){t.cancel()}),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter(function(e){return"object"==typeof e.target&&e.target.canvas===t});return e.forEach(function(t){t.cancel()}),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach(function(t){t.cancel()}),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find(function(e){return e.cancel===t})},findAnimationsByTarget:function(t){return t?this.filter(function(e){return e.target===t}):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},o=b.window.cancelAnimationFrame||b.window.clearTimeout;function a(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),a(function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map(function(t,e){return v[e]-_[e]}):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-l,r=n/c,w=p?_.map(function(t,e){return m(n,_[e],y[e],c)}):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!o){if(!f(w,C,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(w,C,r),void a(t));h()}}(l)}),s.cancel},b.util.requestAnimFrame=a,b.util.cancelAnimFrame=function(){return o.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),o=new b.Color(i).getSource(),a=r.onComplete,h=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:o,byValue:o,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(a)return a(t(o,o,0),i,n)},onChange:function(e,i,n){if(h){if(Array.isArray(e))return h(t(e,e,0),i,n);h(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-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,r)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,o=[];for(r=0,s=e.length;r1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,C={},E="",S=0,b=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",a=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),n=-parseFloat(l[2]),r=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=o,y?(C.width=r,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/r,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=C.width-r*c,b=C.height-o*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),a=E+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+b)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach(function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))}),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var o,a=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),h=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),l=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,o,a,h=new i,l=n.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),o=n.max(r),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,o,a=e.util.array.max([t,i,n]),h=e.util.array.min([t,i,n]);if(o=(a+h)/2,a===h)r=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case t:r=(i-n)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===l&&t.originY===l}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,n,r);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function w(t,e){return function(i,n,r,s){var o=e(i,n,r,s);return o&&g(t,v(i,n,r,s)),o}}function C(t,i,n,r,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(r,s),i,n);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?r=0:(r=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().y;l.set("skewX",r),S(l,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?r=0:(r=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(r=-r),e.originX===a&&e.originY===o&&(r=-r),E(l)&&(r=-r));var m=g!==r;if(m){var p=l._getTransformedDimensions().x;l.set("skewY",r),S(l,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var o=f(n,e);return i[o]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y(function(t,e,i,n){var r=e,s=r.target,o=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(r.ey-o.y,r.ex-o.x),l=Math.atan2(n-o.y,i-o.x),c=u(l-h+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:a:(c>0&&(r=u===o?s:a),c<0&&(r=u===o?a:s),E(h)&&(r=r===s?a:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?r=C(e,l,l,i,n).y>0?o:h:(c>0&&(r=u===s?o:h),c<0&&(r=u===s?h:o),E(a)&&(r=r===o?h:o)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,o=n-e.offsetY,a=!r.get("lockMovementX")&&r.left!==s,h=!r.get("lockMovementY")&&r.top!==o;return a&&r.set("left",s),h&&r.set("top",o),(a||h)&&g("moving",v(t,e,i,n)),a||h},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,o=this.sizeX||n.cornerSize||r.cornerSize,a=this.sizeY||n.cornerSize||r.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(m),l=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:n-l,y:r-h},tr:{x:n+o,y:r-a},bl:{x:n-o,y:r+a},br:{x:n+l,y:r+h}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:a,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach(function(e){i[e]=t[e]}),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort(function(t,e){return t.offset-e.offset}),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),n=0,r=h.length;n0){var p=m/Math.max(a.r1,a.r2);for(n=0,r=h.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],s));return l=b.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach(function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s})}(0,a,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,function(t,n){i.source=t,e&&e(i,n)},null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(o.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(o.y)+this.blur)/t.height,s)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach(function(e){this[e]!==i[e]&&(t[e]=this[e])},this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,o=b.util.getNodeCanvas,a=b.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)},this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=b.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+n(-i[4]/i[0],a)+" "+n(-i[5]/i[3],a)+" "+n(this.width/i[0],a)+" "+n(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map(function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}}).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,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,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,r),this._objects.splice(o,0,r)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(n=(a=h._objects).length;n--;)r=a[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(o=t[i],a.push(o));return a.push(t[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,b.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find(function(e){return!0===t[e]}):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,o=i.controls[s],a=n&&s?o.getActionHandler(t,i,o):b.controlsUtils.dragHandler,h=this._getActionFromCorner(n,s,t,i),l=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),o=Math.min(n.x,s.x),a=Math.min(n.y,s.y),h=Math.max(n.x,s.x),l=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;n=o,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();return 1!==l&&(r.x/=l,r.y/=l),n=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach(function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))}),n.forEach(function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))}),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach(function(i){e[i]=t[i]}),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach(function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})}),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach(function(t){t.isEditing&&t.hiddenTextarea.focus()})},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0},400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,o=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,o=r+this._groupSelector.top,a=new b.Point(v(n,s),v(r,o)),h=new b.Point(y(n,s),y(r,o)),l=!this.selectionFullyContained,c=n===s&&r===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter(function(e){return!e.onSelect({e:t})})),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,o=this.height,a=r*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,function(t){r.clear(),r._setBgOverlay(n,function(){s?r._enlivenObjects([s],function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,o,e)}):r.__setupCanvas.call(r,n,t,o,e)})},i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach(function(t,e){r.insertAt(t,e)}),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],function(e){r[t]=e[0],i[t]=!0,n&&n()}):this["set"+b.util.string.capitalize(t,!0)](e,function(){i[t]=!0,n&&n()})},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},null,i):e&&e([])},_toDataURL:function(t,e){this.clone(function(i){e(i.toDataURL(t))})},_toDataURLWithMultiplier:function(t,e,i){this.clone(function(n){i(n.toDataURLWithMultiplier(t,e))})},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData(function(e){e.loadFromJSON(i,function(){t&&t(e)})})},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,function(){i.renderAll(),t&&t(i)}),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=l>y||c>w;v=C||(l<.9*y||c<.9*w)&&y>h&&w>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),r=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-r)+r,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach(function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])}),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),n=e.util.qrDecompose(h),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(o(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,o=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=r.x/this.scaleX/o,h=r.y/this.scaleY/o;s.width=a,s.height=h,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(a,0),n.lineTo(a,h),n.lineTo(0,h),n.closePath(),n.translate(a/2,h/2),n.scale(r.zoomX/this.scaleX/o,r.zoomY/this.scaleY/o),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/r.zoomX,o*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),m.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,o(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var o=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,function(){var t=s?new o(i[s],i):new o(i);r&&r(t)})})},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,o=r-i,((s=n-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*a.x,l=t.y+o*a.y),new b.Point(h,l)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,o=b.util.sin(n)*r;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some(function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y})||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every(function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)})&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var o in e)if(!((r=e[o]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,o=r?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach(function(t){r[t]=e[t]}),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;h--)if(r=a[h],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:o},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),o&&(t.beginPath(),this.forEachControl(function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(a=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))}),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=n.x+r*(s?this.canvas.getZoom():e.scaleX)+o,h=n.y+r*(s?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl(function(r,s,o){n=o.oCoords[s],r.getVisibility(o,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,o))}),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,a=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,o,a){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return o?b.util.animateColor(h.startValue,h.endValue,h.duration,h):b.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(n),this.get(r));case a:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case h:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(o,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,function(t){delete t.points,i&&i(t)},"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=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 n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+n-e,o),a&&t.bezierCurveTo(s+n-h*e,o,s+n,o+h*i,s+n,o+i),t.lineTo(s+n,o+r-i),a&&t.bezierCurveTo(s+n,o+r-h*i,s+n-h*e,o+r,s+n-e,o+r),t.lineTo(s+e,o+r),a&&t.bezierCurveTo(s+h*e,o+r,s,o+r-h*i,s,o+r-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new e.Rect(i(r?e.util.object.clone(r):{},s));o.visible=o.visible&&o.width>0&&o.height>0,n(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map(function(t){return t.slice()})})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter(function(t){return!t.excludeFromExport}).map(function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r}),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map(function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n})}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),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,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)},this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var o=b.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter(function(t){return t&&!t.isNeutralState()}),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*n,g=o(r*i,c-d),m=o(s*n,u-f),p=-r/2,_=-s/2,v=o(r,c/i-h),y=o(s,u/n-l);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,function(t){e&&e(t)},"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-n*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=n-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,function(){var n=new b.Image(t,i);e(n,!1)})})})},null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,function(t,n){e&&e(new b.Image(t,i),n)},null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(n,s[o])){b.webGlPrecision=s[o];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var o=b.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=x);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),x.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:a,sourceTexture:this.createTexture(a,i,n,!o&&e),targetTexture:this.createTexture(a,i,n),originalTexture:o||this.createTexture(a,i,n,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach(function(t){t&&t.applyTo(h)}),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),r.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var o={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach(function(t){t.applyTo(o)}),o.imageData.width===i&&o.imageData.height===n||(r.width=o.imageData.width,r.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=w||o<0||o>=y||(h=4*(a*y+o),l=p[f*_+d],e+=m[h]*l,i+=m[h+1]*l,n+=m[h+2]*l,S||(r+=m[h+3]*l));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;el[0]&&r>l[1]&&s>l[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,n=h[1]*this.alpha,r=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,a=e.height,h=o(s*i),l=o(a*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,a,h,l)),t.imageData=r},sliceByTwo:function(t,i,r,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((a=m.sliceByTwo).width<1.5*i||a.height=e)){L=n(1e3*s(b-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=o||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(S*a+h)]=O/x,d[I+1]=R/x,d[I+2]=A/x,d[I+3]=D/x}return++h1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],o=1/n[1],a=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,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,n){var r=t+i.kernedWidth/2,s=this.path,o=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=o.x-n.x,i.renderTop=o.y-n.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,o=this.getCompleteStyleDeclaration(e,i),a=n?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,n,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),l&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,_=p,n=r,o=a}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,o=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,o=0,a=this.get2DCursorLocation(t);n=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(n,r,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(n),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===a&&(m=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))})},initRemovedHandler:function(){var t=this;this.on("removed",function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))})},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach(function(t){t.__isMousedown=!1})},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout(function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")},100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout(function(){e._tick()},i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return h=b.util.transformPoint(h,a),(h=b.util.transformPoint(h,this.canvas.viewportTransform)).x*=m,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),o=r.lineIndex,a=r.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(r[a+i]=s[a],s[a-i]||delete r[a])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var h=r[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(h)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,o=0;o0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),o=1;o0?this.insertCharStyleObject(n.lineIndex+o,0,r[o],i):i&&this.styles[n.lineIndex+o]&&i[0]&&(this.styles[n.lineIndex+o][0]=i[0]),i=i&&i.slice(r[o]+1);r[o]>0&&this.insertCharStyleObject(n.lineIndex+o,0,r[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));r=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||o<0?0:1);return this.flipX&&(a=r-a),a>this._text.length&&(a=this._text.length),a}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r+1,o);return this._textLines[r].slice(s).length+a+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,o=this._getWidthBeforeCursor(r,s),a=this._getIndexOnLine(r-1,o),h=this._textLines[r].slice(0,s),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=r.length;ae){n=!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 n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var o=0,a=this._textLines.length;o",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)h=g===m||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(r,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,o){var a=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,n=s.offset),o&&(r=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=n&&(!r||hn&&!p?(a.push(h),h=[],s=f,p=!0):s+=_,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&a.push(h),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},li={};function ci(t){var e=li[t];if(void 0!==e)return e.exports;var i=li[t]={exports:{}};return hi[t](i,i.exports,ci),i.exports}ci.d=(t,e)=>{for(var i in e)ci.o(e,i)&&!ci.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ci.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ui={};(()=>{let t;ci.d(ui,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ci(653).fabric:{version:"5.2.1"}})();var di,fi,gi,mi,pi=ui.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"}(di||(di={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(fi||(fi={})),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"}(gi||(gi={})),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"}(mi||(mi={}));const _i=t=>"number"==typeof t&&!Number.isNaN(t),vi=t=>"string"==typeof t;var yi,wi,Ci,Ei,Si,bi,Ti,Ii,xi,Oi,Ri;!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"}(Si||(Si={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(bi||(bi={}));let Ai=class{get mediaType(){return new Map([["rect",di.DIMT_RECTANGLE],["quad",di.DIMT_QUADRILATERAL],["text",di.DIMT_TEXT],["arc",di.DIMT_ARC],["image",di.DIMT_IMAGE],["polygon",di.DIMT_POLYGON],["line",di.DIMT_LINE],["group",di.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(ii(this,wi,"f")){case fi.DIS_DEFAULT:return"default";case fi.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"===ii(this,Ci,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===ii(this,Ci,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),ni(this,Ci,t,"f")}get coordinateBase(){return ii(this,Ci,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(yi.add(this),wi.set(this,void 0),Ci.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&&!_i(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(fi.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",()=>{this.setState(fi.DIS_SELECTED)}),this._fabricObject.on("deselected",()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(fi.DIS_SELECTED):this.setState(fi.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){ni(this,wi,t,"f")}getState(){return ii(this,wi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,r=t+window.scrollX,s=e+window.scrollY;const{width:a,height:h}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),l=this._drawingLayer.width,c=this._drawingLayer.height,u=a/h,d=l/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Fi),actionName:"modifyPolygon",pointIndex:i}),t},{}),ni(this,Ii,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map(t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2})),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce(function(t,e,n){return t["p"+n]=new pi.Control({positionHandler:Li,actionHandler:Pi(n>0?n-1:i,Fi),actionName:"modifyPolygon",pointIndex:n}),t},{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=pi.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map(t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map(t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){ii(this,Ii,"f")&&this.setPolygon(ii(this,Ii,"f"))}setPolygon(t){if(!P(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 ni(this,Ii,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 ii(this,Ii,"f")?JSON.parse(JSON.stringify(ii(this,Ii,"f"))):null}};Ii=new WeakMap;let Ni=class extends Ai{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return ii(this,Oi,"f")}constructor(t,e,i,n){if(super(null,n),xi.set(this,void 0),Oi.set(this,void 0),!N(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new pi.Image(t,{left:e.x,top:e.y}));else{if(!A(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===_.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map(t=>t.split("\t")))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2})),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce(function(t,e,i){return t["p"+i]=new pi.Control({positionHandler:Li,actionHandler:Pi(i>0?i-1:n,Fi),actionName:"modifyPolygon",pointIndex:i}),t},{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=pi.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){ii(this,Ui,"f")&&this.setLine(ii(this,Ui,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!M(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 ni(this,Ui,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 ii(this,Ui,"f")?JSON.parse(JSON.stringify(ii(this,Ui,"f"))):null}};Ui=new WeakMap;class Wi extends ki{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Vi.set(this,void 0),!k(t))throw new TypeError("Invalid 'quad'.");ni(this,Vi,JSON.parse(JSON.stringify(t)),"f"),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){ii(this,Vi,"f")&&this.setQuad(ii(this,Vi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!k(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 ni(this,Vi,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 ii(this,Vi,"f")?JSON.parse(JSON.stringify(ii(this,Vi,"f"))):null}}Vi=new WeakMap;let Yi=class extends Ai{constructor(t){super(new pi.Group(t.map(t=>t._getFabricObject()))),this._fabricObject.on("selected",()=>{this.setState(fi.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(fi.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout(()=>{e&&e.fire("deselected")},0);setTimeout(()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())},0)}),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map(t=>t.getDrawingItem())}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}};const Hi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Xi=t=>!!vi(t)&&""!==t,zi=t=>!(!Hi(t)||"id"in t&&!_i(t.id)||"lineWidth"in t&&!_i(t.lineWidth)||"fillStyle"in t&&!Xi(t.fillStyle)||"strokeStyle"in t&&!Xi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Xi(t.fontFamily)||"fontSize"in t&&!_i(t.fontSize));class qi{static convert(t,e,i,n){const r={x:0,y:0,width:e,height:i};if(!t)return r;const s=n.getVideoFit(),o=n.getVisibleRegionOfVideo({inPixels:!0});if(N(t))t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.x/100*e,r.y=t.y/100*i,r.width=t.width/100*e,r.height=t.height/100*i):(r.x=o.x+t.x/100*o.width,r.y=o.y+t.y/100*o.height,r.width=t.width/100*o.width,r.height=t.height/100*o.height):"contain"===s||null===o?(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height):(r.x=t.x+o.x,r.y=t.y+o.y,r.width=t.width>o.width?o.width:t.width,r.height=t.height>o.height?o.height:t.height);else{if(!D(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?"contain"===s||null===o?(r.x=t.left/100*e,r.y=t.top/100*i,r.width=(t.right-t.left)/100*e,r.height=(t.bottom-t.top)/100*i):(r.x=o.x+t.left/100*o.width,r.y=o.y+t.top/100*o.height,r.width=(t.right-t.left)/100*o.width,r.height=(t.bottom-t.top)/100*o.height):"contain"===s||null===o?(r.x=t.left,r.y=t.top,r.width=t.right-t.left,r.height=t.bottom-t.top):(r.x=t.left+o.x,r.y=t.top+o.y,r.width=t.right-t.left>o.width?o.width:t.right-t.left,r.height=t.bottom-t.top>o.height?o.height:t.bottom-t.top)}return r.x=Math.round(r.x),r.y=Math.round(r.y),r.width=Math.round(r.width),r.height=Math.round(r.height),r}}var Ki,Zi;class Ji{constructor(){Ki.set(this,new Map),Zi.set(this,!1)}get disposed(){return ii(this,Zi,"f")}on(t,e){t=t.toLowerCase();const i=ii(this,Ki,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else ii(this,Ki,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=ii(this,Ki,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=ii(this,Ki,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=ii(this,Ki,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let o=!1;if(i.async)setTimeout(()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)},0);else try{o=r.apply(i.target,s)}catch(t){}if(!0===o)break}}}dispose(){ni(this,Zi,!0,"f")}}function $i(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 Qi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function tn(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Ki=new WeakMap,Zi=new WeakMap;const en=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};class nn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce((t,e,i)=>t+e*r[i],0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return nn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return nn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return nn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var rn,sn,on,an,hn,ln,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,In,xn,On,Rn,An,Dn,Ln,Mn,Fn,Pn,kn,Nn,Bn,jn,Un,Vn,Gn,Wn,Yn,Hn,Xn,zn,qn,Kn,Zn,Jn,$n,Qn,tr,er,ir,nr,rr,sr,or,ar,hr,lr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,br,Tr,Ir,xr,Or,Rr,Ar,Dr;class Lr{static createDrawingStyle(t){if(!zi(t))throw new Error("Invalid style definition.");let e,i=Lr.USER_START_STYLE_ID;for(;ii(Lr,rn,"f",sn).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in ii(Lr,rn,"f",on))n.hasOwnProperty(t)||(n[t]=ii(Lr,rn,"f",on)[t]);return ii(Lr,rn,"f",sn).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=ii(Lr,rn,"f",sn).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(ii(Lr,rn,"f",sn).values())))}static _updateDrawingStyle(t,e){if(!zi(e))throw new Error("Invalid style definition.");const i=ii(Lr,rn,"f",sn).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}rn=Lr,Lr.STYLE_BLUE_STROKE=1,Lr.STYLE_GREEN_STROKE=2,Lr.STYLE_ORANGE_STROKE=3,Lr.STYLE_YELLOW_STROKE=4,Lr.STYLE_BLUE_STROKE_FILL=5,Lr.STYLE_GREEN_STROKE_FILL=6,Lr.STYLE_ORANGE_STROKE_FILL=7,Lr.STYLE_YELLOW_STROKE_FILL=8,Lr.STYLE_BLUE_STROKE_TRANSPARENT=9,Lr.STYLE_GREEN_STROKE_TRANSPARENT=10,Lr.STYLE_ORANGE_STROKE_TRANSPARENT=11,Lr.USER_START_STYLE_ID=1024,sn={value:new Map([[Lr.STYLE_BLUE_STROKE,{id:Lr.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_GREEN_STROKE,{id:Lr.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}],[Lr.STYLE_ORANGE_STROKE,{id:Lr.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}],[Lr.STYLE_YELLOW_STROKE,{id:Lr.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_BLUE_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_GREEN_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_ORANGE_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_YELLOW_STROKE_FILL,{id:Lr.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}],[Lr.STYLE_BLUE_STROKE_TRANSPARENT,{id:Lr.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_GREEN_STROKE_TRANSPARENT,{id:Lr.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Lr.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Lr.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},on={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&&(pi.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(pi.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),pi.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},pi.Object.prototype.transparentCorners=!1,pi.Object.prototype.cornerSize=20,pi.Object.prototype.touchCornerSize=100,pi.Object.prototype.cornerColor="rgb(254,142,20)",pi.Object.prototype.cornerStyle="circle",pi.Object.prototype.strokeUniform=!0,pi.Object.prototype.hasBorders=!1,pi.Canvas.prototype.containerClass="",pi.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i=this.upperCanvasEl;let n,r=pi.util.getPointer(t,i),s=i.getBoundingClientRect(),o=s.width||0,a=s.height||0;o&&a||("top"in s&&"bottom"in s&&(a=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(o=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();if(1!==h&&(r.x/=h,r.y/=h),0!==o&&0!==a){var l=window.getComputedStyle(i).objectFit,c=i.width,u=i.height,d=o,f=a;n={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===l?p>_?(g=d,m=d/p,{x:r.x*n.width,y:(r.y-(f-m)/2)*n.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*n.height,y:r.y*n.height}):"cover"===l?p>_?{x:(c-n.height*d)/2+r.x*n.height,y:r.y*n.height}:{x:r.x*n.width,y:(u-n.width*f)/2+r.y*n.width}:{x:r.x*n.width,y:r.y*n.height}}return n={width:1,height:1},{x:r.x*n.width,y:r.y*n.height}},pi.Canvas.prototype._onTouchStart=function(t){let e;for(let i=0;ii&&!_?(h.push(l),l=[],o=g,_=!0):o+=v,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&h.push(l),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),h});class Mr{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 pi.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])},0)}}),e.on("before:selection:cleared",function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout(()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)},0)}}),e.on("selection:updated",function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout(()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)},0)}}),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.fabricCanvas.id=e,this.id=e,e){case Mr.DDN_LAYER_ID:n=Lr.getDrawingStyle(Lr.STYLE_BLUE_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_BLUE_STROKE_FILL);break;case Mr.DBR_LAYER_ID:n=Lr.getDrawingStyle(Lr.STYLE_ORANGE_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_ORANGE_STROKE_FILL);break;case Mr.DLR_LAYER_ID:n=Lr.getDrawingStyle(Lr.STYLE_GREEN_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_GREEN_STROKE_FILL);break;default:n=Lr.getDrawingStyle(Lr.STYLE_YELLOW_STROKE),r=Lr.getDrawingStyle(Lr.STYLE_YELLOW_STROKE_FILL)}for(let t of Ai.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Lr.getDrawingStyle(t.styleId);return Lr.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems(e=>e._mediaType===t);for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Lr.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Lr.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Lr.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof Ai))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ai.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Lr.getDrawingStyle(t.styleId);else{s=Lr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of Ai.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Lr.getDrawingStyle(t.styleId);else{s=Lr.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Lr.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=n.length;if(o)a=n.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;et.toLowerCase()):e=Ai.arrMediaTypes,i?i.forEach(t=>t.toLowerCase()):i=Ai.arrStyleSelectors;const n=Lr.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&di.DIMT_RECTANGLE&&n.push("rect"),i&di.DIMT_QUADRILATERAL&&n.push("quad"),i&di.DIMT_TEXT&&n.push("text"),i&di.DIMT_ARC&&n.push("arc"),i&di.DIMT_IMAGE&&n.push("image"),i&di.DIMT_POLYGON&&n.push("polygon"),i&di.DIMT_LINE&&n.push("line");const r=[];e&fi.DIS_DEFAULT&&r.push("default"),e&fi.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Mr.DDN_LAYER_ID=1,Mr.DBR_LAYER_ID=2,Mr.DLR_LAYER_ID=3,Mr.USER_DEFINED_LAYER_BASE_ID=100,Mr.TIP_LAYER_ID=999;class Fr{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Mr(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 Pr extends ji{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),an.set(this,void 0),hn.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&ni(this,hn,setTimeout(()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()},ii(this,an,"f")),"f")}getDuration(){return ii(this,an,"f")}}an=new WeakMap,hn=new WeakMap;class kr{constructor(){ln.add(this),cn.set(this,void 0),un.set(this,void 0),dn.set(this,void 0),fn.set(this,!0),this._drawingLayerManager=new Fr}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Mr.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Mr.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()!==Mr.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(!(Hi(e=t)&&F(e.topLeftPoint)&&_i(e.width))||e.width<=0||!_i(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;ni(this,cn,JSON.parse(JSON.stringify(t)),"f"),ii(this,cn,"f").coordinateBase||(ii(this,cn,"f").coordinateBase="view"),ni(this,dn,t.duration,"f"),ii(this,ln,"m",_n).call(this)}getTipConfig(){return ii(this,cn,"f")?ii(this,cn,"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()),ni(this,fn,t,"f")}isTipVisible(){return ii(this,fn,"f")}updateTipMessage(t){if(!ii(this,cn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Lr.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Mr.TIP_LAYER_ID)||this._createDrawingLayer(Mr.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=ii(this,ln,"m",gn).call(this,t,ii(this,cn,"f").topLeftPoint.x,ii(this,cn,"f").topLeftPoint.y,ii(this,cn,"f").width,ii(this,cn,"f").coordinateBase,this._tipStyleId),ii(this,ln,"m",mn).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",ii(this,fn,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),ii(this,un,"f")&&clearTimeout(ii(this,un,"f")),ii(this,dn,"f")>=0&&ni(this,un,setTimeout(()=>{ii(this,ln,"m",pn).call(this)},ii(this,dn,"f")),"f")}}cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,ln=new WeakSet,gn=function(t,e,i,n,r,s){const o=new Pr(t,e,i,n,s);return o.coordinateBase=r,o},mn=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},pn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},_n=function(){if(!this._tip)return;const t=ii(this,cn,"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 Nr extends HTMLElement{constructor(){super(),vn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),ni(this,vn,e,"f");const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return ii(this,vn,"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())}}vn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Nr);class Br extends kr{static get engineResourcePath(){const t=V(Ht.engineResourcePaths);return"DCV"===Ht._bundleEnv?t.dcvData+"ui/":t.dbrBundle+"ui/"}static set defaultUIElementURL(t){Br._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Br._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Br.engineResourcePath)}static async createInstance(t){const e=new Br;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Br.engineResourcePath)),await e.setUIElement(t||Br.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,o){const a=s/n,h=o/r;t.x=Math.round(t.x/a+e),t.y=Math.round(t.y/h+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==ii(this,On,"f")){if(ni(this,On,t,"f"),ii(this,yn,"m",Dn).call(this))ni(this,Sn,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"),!ii(this,Sn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ti.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ni(this,Sn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}ii(this,yn,"m",Dn).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 ii(this,On,"f")}get disposed(){return ii(this,An,"f")}constructor(){super(),yn.add(this),wn.set(this,void 0),Cn.set(this,void 0),En.set(this,void 0),this._poweredByVisible=!0,this.containerClassName="dce-video-container",Sn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._poweredBy=null,bn.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,Tn.set(this,!1),In.set(this,!1),xn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{ii(this,yn,"m",kn).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()&&ii(this,yn,"m",Pn).call(this))},this._updateLayersTimeout)},this._windowResizeListener=()=>{Br._onLog&&Br._onLog("window resize event triggered."),ii(this,xn,"f").width===document.documentElement.clientWidth&&ii(this,xn,"f").height===document.documentElement.clientHeight||(ii(this,xn,"f").width=document.documentElement.clientWidth,ii(this,xn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},On.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!ii(this,yn,"m",Dn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=this._cvsSingleFrameMode;const a=null==o?void 0:o.width,h=null==o?void 0:o.height;o||(o=document.createElement("canvas"),this._cvsSingleFrameMode=o),i(o,n,r,s),this._innerComponent.setElement("content",o),a===o.width&&h===o.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout(()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)},0)}),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},Rn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const o=t.originalImageTag;if(!o)return;const a=t.items;if(!(null==a?void 0:a.length))return;const h=(null===(i=o.cropRegion)||void 0===i?void 0:i.left)||0,l=(null===(n=o.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=o.cropRegion)||void 0===r?void 0:r.right)?o.cropRegion.right-h:o.originalWidth,u=(null===(s=o.cropRegion)||void 0===s?void 0:s.bottom)?o.cropRegion.bottom-l:o.originalHeight,d=o.currentWidth,f=o.currentHeight,g=(t,e,i,n,r,s,o,a,h=[],l)=>{(e=JSON.parse(JSON.stringify(e))).forEach(t=>Br._transformCoordinates(t,i,n,r,s,o,a));const c=new Wi({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]),ii(this,Rn,"f").push(c)};let m,p;for(let t of a)switch(t.type){case ft.CRIT_ORIGINAL_IMAGE:break;case ft.CRIT_BARCODE:m=this.getDrawingLayer(Mr.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,Lr.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_TEXT_LINE:m=this.getDrawingLayer(Mr.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,Lr.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,p);break;case ft.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Mr.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.location.points,h,l,c,u,d,f,[]):g(m,t.location.points,h,l,c,u,d,f,[],Lr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,h,l,c,u,d,f,[]);break;case ft.CRIT_DESKEWED_IMAGE:m=this.getDrawingLayer(Mr.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===Ct.CVS_PASSED?g(m,t.sourceLocation.points,h,l,c,u,d,f,[]):g(m,t.sourceLocation.points,h,l,c,u,d,f,[],Lr.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.sourceLocation.points,h,l,c,u,d,f,[]);break;case ft.CRIT_PARSED_RESULT:case ft.CRIT_ENHANCED_IMAGE:break;default:throw new Error("Illegal item type.")}}},An.set(this,!1),this.eventHandler=new Ji,this.eventHandler.on("content:updated",()=>{ii(this,wn,"f")&&clearTimeout(ii(this,wn,"f")),ni(this,wn,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",()=>{ii(this,Cn,"f")&&clearTimeout(ii(this,Cn,"f")),ni(this,Cn,setTimeout(()=>{this.disposed||this._updateVideoContainer()},0),"f")})}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await en(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),ii(this,yn,"m",Dn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("crossOrigin","anonymous"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ti.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),ni(this,Sn,t,"f");const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._poweredBy=i.querySelector(".dce-msg-poweredby"),this._selRsl&&(this._hideDefaultSelection||ii(this,yn,"m",Dn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||ii(this,yn,"m",Dn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||ii(this,yn,"m",kn).call(this),ii(this,yn,"m",Dn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),ii(this,yn,"m",Dn).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;Br._onLog&&Br._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()}));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}ii(this,xn,"f").width=document.documentElement.clientWidth,ii(this,xn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;ii(this,yn,"m",Dn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),ii(this,yn,"m",kn).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,ni(this,Sn,null,"f"),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return ii(this,Sn,"f")}isVideoLoaded(){return this.cameraEnhancer.cameraManager.isVideoLoaded()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!ii(this,Sn,"f"))return;if(ii(this,Sn,"f").style.objectFit=t,ii(this,yn,"m",Dn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e);const i=this.getConvertedRegion();ii(this,yn,"m",Nn).call(this,e,i),ii(this,yn,"m",Ln).call(this,e,i),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,o;if(ii(this,yn,"m",Dn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,o="contain"):(r=null===(t=ii(this,Sn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=ii(this,Sn,"f"))||void 0===e?void 0:e.videoHeight,o=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:o}}updateConvertedRegion(t){D(this.scanRegion)?this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.top&&100===this.scanRegion.bottom&&0===this.scanRegion.left&&100===this.scanRegion.right&&(this.scanRegion=null):0===this.scanRegion.top&&this.scanRegion.bottom===t.height&&0===this.scanRegion.left&&this.scanRegion.right===t.width&&(this.scanRegion=null):N(this.scanRegion)&&(this.scanRegion.isMeasuredInPercentage?0===this.scanRegion.x&&0===this.scanRegion.y&&100===this.scanRegion.width&&100===this.scanRegion.height&&(this.scanRegion=null):0===this.scanRegion.x&&0===this.scanRegion.y&&this.scanRegion.width===t.width&&this.scanRegion.height===t.height&&(this.scanRegion=null));const e=qi.convert(this.scanRegion,t.width,t.height,this);ni(this,bn,e,"f"),ii(this,En,"f")&&clearTimeout(ii(this,En,"f")),ni(this,En,setTimeout(()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}ii(this,yn,"m",Ln).call(this,t,e),ii(this,yn,"m",Nn).call(this,t,e)},0),"f")}getConvertedRegion(){return ii(this,bn,"f")}setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if("disabled"!==this.cameraEnhancer.singleFrameMode)return null;if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=ii(this,Sn,"f").videoWidth,i=ii(this,Sn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)return null;let o;const a={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=ii(this,Sn,"f").videoWidth,e=ii(this,Sn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove()),ii(this,Rn,"f").length=0}dispose(){this._unbindUI(),ni(this,An,!0,"f")}}wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Sn=new WeakMap,bn=new WeakMap,Tn=new WeakMap,In=new WeakMap,xn=new WeakMap,On=new WeakMap,Rn=new WeakMap,An=new WeakMap,yn=new WeakSet,Dn=function(){return"disabled"!==this._singleFrameMode},Ln=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)},Mn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},Fn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Pn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},kn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Nn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:o}=this._innerComponent.getBoundingClientRect();if(s<=0||o<=0)return;const a=s/o,h=i/n;let l,c,u,d,f=1;if("contain"===r)a{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach(e=>t.attachShader(i,e)),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,a)]);ni(this,Un,{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"),ni(this,Vn,e(t),"f"),ni(this,jn,i(t),"f"),ni(this,Bn,p,"f")}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},v=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},y=(t,e,o,m)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,o.positions,e.attribLocations.vertexPosition),r(t,o.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,m),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[mi.GREY,mi.GREY32].includes(p)?1:0);let _,v,y=nn.translate(nn.identity(),-1,-1);y=nn.scale(y,2,2),y=nn.scale(y,1/t.canvas.width,1/t.canvas.height),_=nn.translate(y,u,d),_=nn.scale(_,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,_),s.isEnableMirroring?(v=nn.translate(nn.identity(),1,0),v=nn.scale(v,-1,1),v=nn.translate(v,a/i,h/n),v=nn.scale(v,l/i,c/n)):(v=nn.translate(nn.identity(),a/i,h/n),v=nn.scale(v,l/i,c/n)),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};v(t,ii(this,jn,"f"),e),y(t,ii(this,Un,"f"),ii(this,Vn,"f"),ii(this,jn,"f"));const w=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,w),255!==w[3]){jr._onLog&&jr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return jr._onLog&&jr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-o)),{context:t,pixelFormat:p===mi.GREY?mi.GREY32:p,bUseWebGL:!0}}catch(o){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return jr._onLog&&jr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw o.name="WebGLError",o}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,o=t.canvas.width,a=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(o=e.width),e.height&&(a=e.height)),(null==i?void 0:i.length)<4*o*a)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*o*a)):(n=new Uint8Array(4*o*a),e.readPixels(r,s,o,a,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,o,a),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(jr._onLog&&(r=Date.now(),jr._onLog("transformPixelFormat(), START: "+r)),e===i)return jr._onLog&&jr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const o=[mi.RGBA,mi.RBGA,mi.GRBA,mi.GBRA,mi.BRGA,mi.BGRA];if(o.includes(e))if(i===mi.GREY){s=new Uint8Array(t.length/4);for(let e=0;eh||e.sy+e.sHeight>l)throw new Error("Invalid position.");null===(n=jr._onLog)||void 0===n||n.call(jr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||mi.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(mi.GREY===y&&w.length{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Vr{static get version(){return"4.3.3-dev-20251029130621"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find(t=>e.includes(t.label.toLowerCase()));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter(t=>{const i=t.label.toLowerCase();return e.some(t=>i.includes(t))});if(!r.length)return null;const s=r.find(t=>{const e=t.label.toLowerCase();return i.some(t=>e.includes(t))});if(s)return s.deviceId;const o=r.find(t=>{const e=t.label.toLowerCase();return n.some(t=>e.includes(t))});return o?o.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(ti.OS))return Vr.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(ti.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise(async(n,r)=>{let s;const o=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let a=!1;const h=()=>{a=!0,s&&clearTimeout(s),o(),n(t)},l=t=>{s&&clearTimeout(s),o(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",l(t)},d=()=>{h()},f=()=>{l(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise(t=>{g=t}),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise(t=>{setTimeout(t,1e3)}),!a){i&&(s=setTimeout(()=>{o(),r(new Error("Failed to play video. Timeout."))},i)),await m;try{await t.play(),h()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!a)try{await t.play(),h()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),l(t)}}})}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach(t=>{t.stop()})}return{ok:!0}}get state(){if(!ii(this,nr,"f"))return"closed";if("pending"===ii(this,nr,"f"))return"opening";if("fulfilled"===ii(this,nr,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Vr.isStorageAvailable("localStorage")?ni(this,Qn,!0,"f"):(ni(this,Qn,!1,"f"),console.warn("Local storage is unavailable")):ni(this,Qn,!1,"f")}get ifSaveLastUsedCamera(){return ii(this,Qn,"f")}get isVideoPlaying(){return!(!ii(this,Xn,"f")||ii(this,Xn,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=ii(this,lr,"f"))||void 0===e||e.removeEventListener("click",ii(this,hr,"f")),null===(i=ii(this,lr,"f"))||void 0===i||i.removeEventListener("touchend",ii(this,hr,"f")),null===(n=ii(this,lr,"f"))||void 0===n||n.removeEventListener("touchmove",ii(this,ar,"f")),ni(this,lr,t,"f"),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(ti.OS)?(t.addEventListener("touchend",ii(this,hr,"f")),t.addEventListener("touchmove",ii(this,ar,"f"))):t.addEventListener("click",ii(this,hr,"f")))}get tapFocusEventBoundEl(){return ii(this,lr,"f")}get disposed(){return ii(this,vr,"f")}constructor(t){var e,i;Hn.add(this),Xn.set(this,null),zn.set(this,void 0),this._zoomPreSetting=null,qn.set(this,()=>{"opened"===this.state&&ii(this,fr,"f").fire("resumed",null,{target:this,async:!1})}),Kn.set(this,()=>{ii(this,fr,"f").fire("paused",null,{target:this,async:!1})}),Zn.set(this,void 0),Jn.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],$n.set(this,void 0),Qn.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,tr.set(this,void 0),er.set(this,!0),ir.set(this,void 0),nr.set(this,void 0),rr.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},sr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(ii(this,Xn,"f")).objectFit,s=this.getResolution(),o=ii(this,Xn,"f").getBoundingClientRect(),a=o.left,h=o.top,{width:l,height:c}=ii(this,Xn,"f").getBoundingClientRect();if(l<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=l/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=l/s.width,i=(t-a)/f,n=(e-h-(c-l/d)/2)/f):(f=c/s.height,n=(e-h)/f,i=(t-a-(l-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-h)/f,i=(t-a+(c*d-l)/2)/f):(f=l/s.width,i=(t-a)/f,n=(e-h+(l/d-c)/2)/f)}return{x:i,y:n}},or.set(this,!1),ar.set(this,()=>{ni(this,or,!0,"f")}),hr.set(this,async t=>{var e;if(ii(this,or,"f"))return void ni(this,or,!1,"f");if(!ii(this,sr,"f"))return;if(!this.isVideoPlaying)return;if(!ii(this,zn,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let o;try{o=this.calculateCoordInVideo(i,n)}catch(t){}if(o.x<0||o.x>r.width||o.y<0||o.y>r.height)return;const a={x:o.x+"px",y:o.y+"px"},h=s+"px",l=h;let c;Vr._onLog&&(c=Date.now());try{await ii(this,Hn,"m",Rr).call(this,a,h,l,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Vr._onLog)throw Vr._onLog(t),t}Vr._onLog&&Vr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout(()=>{var t;Vr._onLog&&Vr._onLog("Back to continuous focus."),null===(t=ii(this,zn,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})},this._focusParameters.focusBackToContinousTime),ii(this,fr,"f").fire("tapfocus",null,{target:this,async:!1})}),lr.set(this,null),cr.set(this,1),ur.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!ii(this,Xn,"f"))return;const t=ii(this,cr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)ii(this,Xn,"f").style.transform="";else{const e=window.getComputedStyle(ii(this,Xn,"f")).objectFit,i=ii(this,Xn,"f").videoWidth,n=ii(this,Xn,"f").videoHeight,{width:r,height:s}=ii(this,Xn,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const o=r/s,a=i/n;let h=1;"contain"===e?h=oo?s/(i/t):r/(n/t));const l=h*(1-1/t)*(i/2-ii(this,ur,"f").x),c=h*(1-1/t)*(n/2-ii(this,ur,"f").y);ii(this,Xn,"f").style.transform=`translate(${l}px, ${c}px) scale(${t})`}},dr.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===mi.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Vr._onLog&&Vr._onLog("document visible. video paused: "+(null===(t=ii(this,Xn,"f"))||void 0===t?void 0:t.paused)),function(){const t=navigator.userAgent||navigator.vendor||navigator.opera;return!!/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(t)||("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024}())"opened"===this.state&&await ii(this,Hn,"m",Tr).call(this);else if("opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Vr._onLog&&Vr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Vr._onLog&&Vr._onLog("document visible. 1st resume video failed, try open instead.")}e||await ii(this,Hn,"m",Sr).call(this)}if(await new Promise(t=>setTimeout(t,300)),!this.isVideoPlaying){Vr._onLog&&Vr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Vr._onLog&&Vr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await ii(this,Hn,"m",Sr).call(this)}}}else"hidden"===document.visibilityState&&(Vr._onLog&&Vr._onLog("document hidden. video paused: "+(null===(e=ii(this,Xn,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())}),vr.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(()=>{Vr.onWarning&&Vr.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),ni(this,fr,new Ji,"f"),this.imageDataGetter=new jr,document.addEventListener("visibilitychange",ii(this,_r,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",ii(this,qn,"f")),t.addEventListener("pause",ii(this,Kn,"f")),ni(this,Xn,t,"f")}getVideoEl(){return ii(this,Xn,"f")}releaseVideoEl(){var t,e;null===(t=ii(this,Xn,"f"))||void 0===t||t.removeEventListener("play",ii(this,qn,"f")),null===(e=ii(this,Xn,"f"))||void 0===e||e.removeEventListener("pause",ii(this,Kn,"f")),ni(this,Xn,null,"f")}isVideoLoaded(){return!!ii(this,Xn,"f")&&(this.videoSrc?0!==ii(this,Xn,"f").readyState:4===ii(this,Xn,"f").readyState)}async open(){if(ii(this,ir,"f")&&!ii(this,er,"f")){if("pending"===ii(this,nr,"f"))return ii(this,ir,"f");if("fulfilled"===ii(this,nr,"f"))return}ii(this,fr,"f").fire("before:open",null,{target:this}),await ii(this,Hn,"m",Tr).call(this),ii(this,fr,"f").fire("played",null,{target:this,async:!1}),ii(this,fr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;ii(this,fr,"f").fire("before:close",null,{target:this});const t=ii(this,ir,"f");if(ii(this,Hn,"m",Ir).call(this),t&&"pending"===ii(this,nr,"f")){try{await t}catch(t){}if(!1===ii(this,er,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}ni(this,ir,null,"f"),ni(this,nr,null,"f"),ii(this,fr,"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.");ii(this,Xn,"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 ii(this,Xn,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof ii(this,Zn,"f").video&&(ii(this,Zn,"f").video={}),delete ii(this,Zn,"f").video.facingMode,ii(this,Zn,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&ii(this,er,"f"))){ii(this,fr,"f").fire("before:camera:change",[],{target:this,async:!1}),await ii(this,Hn,"m",br).call(this);try{this.resetSoftwareScale()}catch(t){}return ii(this,Jn,"f")}}async switchToFrontCamera(t){if("object"!=typeof ii(this,Zn,"f").video&&(ii(this,Zn,"f").video={}),(null==t?void 0:t.resolution)&&(ii(this,Zn,"f").video.width={ideal:t.resolution.width},ii(this,Zn,"f").video.height={ideal:t.resolution.height}),delete ii(this,Zn,"f").video.deviceId,ii(this,Zn,"f").video.facingMode={exact:"user"},ni(this,$n,null,"f"),!("closed"===this.state||this.videoSrc||"opening"===this.state&&ii(this,er,"f"))){ii(this,fr,"f").fire("before:camera:change",[],{target:this,async:!1}),ii(this,Hn,"m",br).call(this);try{this.resetSoftwareScale()}catch(t){}return ii(this,Jn,"f")}}getCamera(){var t;if(ii(this,Jn,"f"))return ii(this,Jn,"f");{let e=(null===(t=ii(this,Zn,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n=[];if(t)try{let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind),t.getTracks().forEach(t=>{t.stop()})}catch(t){console.error(t.message||t)}else n=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"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 ii(this,Zn,"f").video&&(ii(this,Zn,"f").video={}),i?(ii(this,Zn,"f").video.width={exact:t},ii(this,Zn,"f").video.height={exact:e}):(ii(this,Zn,"f").video.width={ideal:t},ii(this,Zn,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&ii(this,er,"f"))return null;ii(this,fr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await ii(this,Hn,"m",br).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&ii(this,Xn,"f"))return{width:ii(this,Xn,"f").videoWidth,height:ii(this,Xn,"f").videoHeight};if(ii(this,zn,"f")){const t=ii(this,zn,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:ii(this,Xn,"f").videoWidth,height:ii(this,Xn,"f").videoHeight};{const t={width:0,height:0};let e=ii(this,Zn,"f").video.width||0,i=ii(this,Zn,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,o,a,h,l,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=ii(this,mr,"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=ii(this,Jn,"f"))||void 0===u?void 0:u.deviceId;let e=ii(this,mr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],ii(this,mr,"f").set(d,e),ni(this,rr,!0,"f");try{for(let t of this.detectedResolutions){await ii(this,zn,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),ii(this,Hn,"m",wr).call(this);const i=ii(this,zn,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw ii(this,Hn,"m",Ir).call(this),ni(this,rr,!1,"f"),t}try{await ii(this,Hn,"m",Sr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{ni(this,rr,!1,"f")}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach(t=>{t.stop()}),o};let i=(null===(s=null===(r=null===(n=ii(this,Zn,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(h=null===(a=null===(o=ii(this,Zn,"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=ii(this,Zn,"f"))||void 0===l?void 0:l.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=ii(this,mr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],ii(this,mr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");ni(this,Zn,JSON.parse(JSON.stringify(t)),"f"),ni(this,$n,null,"f"),e&&await ii(this,Hn,"m",br).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(ii(this,Zn,"f")))}resetMediaStreamConstraints(){ni(this,Zn,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null,"f")}getCameraCapabilities(){if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ii(this,zn,"f").getCapabilities?ii(this,zn,"f").getCapabilities():{}}getCameraSettings(){if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return ii(this,zn,"f").getSettings()}async turnOnTorch(){if(!ii(this,zn,"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 ii(this,zn,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!ii(this,zn,"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 ii(this,zn,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await ii(this,zn,"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(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await ii(this,zn,"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(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await ii(this,zn,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Ur(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await ii(this,zn,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await ii(this,Hn,"m",Rr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await ii(this,zn,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}enableTapToFocus(){ni(this,sr,!0,"f")}disableTapToFocus(){ni(this,sr,!1,"f")}isTapToFocusEnabled(){return ii(this,sr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"===this.state){t.centerPoint?ii(this,Hn,"m",Ar).call(this,t.centerPoint):this.resetScaleCenter();try{if(ii(this,Hn,"m",Dr).call(this,ii(this,ur,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}else this._zoomPreSetting=t}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*ii(this,cr,"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(!ii(this,zn,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await ii(this,zn,"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&&ii(this,Hn,"m",Ar).call(this,e),ni(this,cr,t,"f"),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return ii(this,cr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();ni(this,ur,{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(ii(this,rr,"f"))return null;const e=Date.now();Vr._onLog&&Vr._onLog("getFrameData() START: "+e);const i=ii(this,Xn,"f").videoWidth,n=ii(this,Xn,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=mi.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let o=ii(this,cr,"f");(null==t?void 0:t.scale)&&(o=t.scale);let a=ii(this,ur,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");a.x=Math.round(e),a.y=Math.round(r)}let h=null;if((null==t?void 0:t.bufferContainer)&&(h=t.bufferContainer),0==i||0==n)return null;1!==o&&(r.sWidth=Math.round(r.sWidth/o),r.sHeight=Math.round(r.sHeight/o),r.sx=Math.round((1-1/o)*a.x+r.sx/o),r.sy=Math.round((1-1/o)*a.y+r.sy/o));const l=this.imageDataGetter.getImageData(ii(this,Xn,"f"),r,{pixelFormat:s,bufferContainer:h,isEnableMirroring:null==t?void 0:t.isEnableMirroring});if(!l)return null;const c=Date.now();return Vr._onLog&&Vr._onLog("getFrameData() END: "+c),{data:l.data,width:l.width,height:l.height,pixelFormat:l.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:ii(this,dr,"f")}}on(t,e){if(!ii(this,gr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);ii(this,fr,"f").on(t,e)}off(t,e){ii(this,fr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),ii(this,fr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",ii(this,_r,"f")),ni(this,vr,!0,"f")}}var Gr,Wr,Yr,Hr,Xr,zr,qr,Kr,Zr,Jr,$r,Qr,ts,es,is,ns,rs,ss,os,as,hs,ls,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,Ss;Xn=new WeakMap,zn=new WeakMap,qn=new WeakMap,Kn=new WeakMap,Zn=new WeakMap,Jn=new WeakMap,$n=new WeakMap,Qn=new WeakMap,tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,or=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,Hn=new WeakSet,yr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(ii(this,$n,"f"))delete t.video.facingMode,t.video.deviceId={exact:ii(this,$n,"f")};else if(this.ifSaveLastUsedCamera&&Vr.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(ti.OS)?(await this._getCameras(!1),ii(this,Hn,"m",wr).call(this),e=Vr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(ti.OS)||(await this._getCameras(!1),ii(this,Hn,"m",wr).call(this),e=Vr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},wr=function(){if(ii(this,er,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Cr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Vr._onLog&&Vr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise(t=>setTimeout(t,r)),ii(this,Hn,"m",wr).call(this));try{Vr._onLog&&Vr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),ii(this,Hn,"m",wr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Vr._onLog&&Vr._onLog(t.message||t)}}};if(await r(t),!n&&"object"==typeof t.video&&!n){const e=(await navigator.mediaDevices.enumerateDevices()).filter(t=>"videoinput"===t.kind);for(let i of e)try{n=await navigator.mediaDevices.getUserMedia({video:{deviceId:{exact:i.deviceId}}});break}catch(t){continue}}if(!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach(t=>{t.stop()}),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Er=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach(t=>{t.stop()}),this._mediaStream=null),ni(this,zn,null,"f")},Sr=async function(){ni(this,er,!1,"f");const t=ni(this,tr,Symbol(),"f");if(ii(this,ir,"f")&&"pending"===ii(this,nr,"f")){try{await ii(this,ir,"f")}catch(t){}ii(this,Hn,"m",wr).call(this)}if(t!==ii(this,tr,"f"))return;const e=ni(this,ir,(async()=>{ni(this,nr,"pending","f");try{if(this.videoSrc){if(!ii(this,Xn,"f"))throw new Error("'videoEl' should be set.");await Vr.playVideo(ii(this,Xn,"f"),this.videoSrc,this.cameraOpenTimeout),ii(this,Hn,"m",wr).call(this)}else{let t=await ii(this,Hn,"m",yr).call(this);ii(this,Hn,"m",Er).call(this);let e=await ii(this,Hn,"m",Cr).call(this,t);await this._getCameras(!1),ii(this,Hn,"m",wr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=ii(this,Zn,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(ii(this,$n,"f")||this.ifSaveLastUsedCamera&&Vr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Vr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach(t=>{t.stop()}),t.video.deviceId={exact:s},e=await ii(this,Hn,"m",Cr).call(this,t),ii(this,Hn,"m",wr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(ni(this,$n,r&&r.deviceId,"f"),this.ifSaveLastUsedCamera&&Vr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",ii(this,$n,"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))))),ii(this,Xn,"f")&&(await Vr.playVideo(ii(this,Xn,"f"),e,this.cameraOpenTimeout),ii(this,Hn,"m",wr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&ni(this,zn,s[0],"f"),ni(this,Jn,r,"f")}}catch(t){throw ii(this,Hn,"m",Ir).call(this),ni(this,nr,null,"f"),t}ni(this,nr,"fulfilled","f")})(),"f");return e},br=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=ii(this,Jn,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await ii(this,Hn,"m",Sr).call(this);const n=this.getResolution();e&&e!==ii(this,Jn,"f").deviceId&&ii(this,fr,"f").fire("camera:changed",[ii(this,Jn,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||ii(this,fr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),ii(this,fr,"f").fire("played",null,{target:this,async:!1})},Tr=async function(){let t=0;for(;Vr._tryToReopenTime>=t++;){try{await ii(this,Hn,"m",Sr).call(this)}catch(t){await new Promise(t=>setTimeout(t,300));continue}break}},Ir=function(){ii(this,Hn,"m",Er).call(this),ni(this,Jn,null,"f"),ii(this,Xn,"f")&&(ii(this,Xn,"f").srcObject=null,this.videoSrc&&(ii(this,Xn,"f").pause(),ii(this,Xn,"f").currentTime=0)),ni(this,er,!0,"f");try{this.resetSoftwareScale()}catch(t){}},xr=async function t(e,i){const n=t=>{if(!ii(this,zn,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){ii(this,zn,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Ur(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await ii(this,zn,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise(t=>{setTimeout(t,r)}),n(e);let s=e.focusL-e.focusW/2,o=e.focusT-e.focusH/2,a=e.focusW,h=e.focusH;const l=this.getResolution();s=Math.round(s),o=Math.round(o),a=Math.round(a),h=Math.round(h),a>l.width&&(a=l.width),h>l.height&&(h=l.height),s<0?s=0:s+a>l.width&&(s=l.width-a),o<0?o=0:o+h>l.height&&(o=l.height-h);const c=4*l.width*l.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*a*h;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(ii(this,Xn,"f"),{sx:s,sy:o,sWidth:a,sHeight:h,dWidth:a,dHeight:h},{pixelFormat:mi.RGBA,bufferContainer:d}))return ii(this,Hn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;ta&&au)return await ii(this,Hn,"m",t).call(this,e,o,a,r,s,c,u)}else{let h=await ii(this,Hn,"m",xr).call(this,e,c);if(a>h)return await ii(this,Hn,"m",t).call(this,e,o,a,r,s,c,h);if(a==h)return await ii(this,Hn,"m",t).call(this,e,o,a,c,h);let u=await ii(this,Hn,"m",xr).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!==ii(this,cr,"f")){const t=ii(this,cr,"f"),e=ii(this,ur,"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 n=Ur(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ur(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ur(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await ii(this,Hn,"m",xr).call(this,t,s),a=await ii(this,Hn,"m",xr).call(this,t,r),h=await ii(this,Hn,"m",xr).call(this,t,n);if(a>h&&ho&&a>o){let e=await ii(this,Hn,"m",xr).call(this,t,i);const r=await ii(this,Hn,"m",Or).call(this,t,n,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,r}if(a==h&&hh){const e=await ii(this,Hn,"m",Or).call(this,t,n,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Ar=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");ni(this,ur,{x:i,y:n},"f")},Dr=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},Vr.browserInfo=ti,Vr._tryToReopenTime=4,Vr.onWarning=null===(Yn=null===window||void 0===window?void 0:window.console)||void 0===Yn?void 0:Yn.warn;class bs{constructor(t){Gr.add(this),Wr.set(this,void 0),Yr.set(this,0),Hr.set(this,void 0),Xr.set(this,0),zr.set(this,!1),ni(this,Wr,t,"f")}startCharging(){ii(this,zr,"f")||(bs._onLog&&bs._onLog("start charging."),ii(this,Gr,"m",Kr).call(this),ni(this,zr,!0,"f"))}stopCharging(){ii(this,Hr,"f")&&clearTimeout(ii(this,Hr,"f")),ii(this,zr,"f")&&(bs._onLog&&bs._onLog("stop charging."),ni(this,Yr,Date.now()-ii(this,Xr,"f"),"f"),ni(this,zr,!1,"f"))}}Wr=new WeakMap,Yr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,zr=new WeakMap,Gr=new WeakSet,qr=function(){Ht.cfd(1),bs._onLog&&bs._onLog("charge 1.")},Kr=function t(){0==ii(this,Yr,"f")&&ii(this,Gr,"m",qr).call(this),ni(this,Xr,Date.now(),"f"),ii(this,Hr,"f")&&clearTimeout(ii(this,Hr,"f")),ni(this,Hr,setTimeout(()=>{ni(this,Yr,0,"f"),ii(this,Gr,"m",t).call(this)},ii(this,Wr,"f")-ii(this,Yr,"f")),"f")};class Ts{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-ii(this,Zr,"f",Qr)<100)){if(ni(this,Zr,e,"f",Qr),ii(this,Zr,"f",Jr).size&&(t=ii(this,Zr,"f",Jr).values().next().value,this.beepSoundSource==t.src?(ii(this,Zr,"f",Jr).delete(t),t.play()):t=null),!t)if(ii(this,Zr,"f",$r).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout(()=>{ii(this,Zr,"f",$r).delete(t)},2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,ii(this,Zr,"f",$r).delete(t),ii(this,Zr,"f",Jr).add(t)})}else ii(this,Zr,"f",ts)||(ni(this,Zr,!0,"f",ts),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&ii(this,Zr,"f",$r).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ts.vibrateDuration)}}}Zr=Ts,Jr={value:new Set},$r={value:new Set},Qr={value:0},ts={value:!1},Ts.allowBeep=!0,Ts.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Ts.allowVibrate=!0,Ts.vibrateDuration=300;const Is=new Map([[mi.GREY,_.IPF_GRAYSCALED],[mi.RGBA,_.IPF_ABGR_8888]]),xs="function"==typeof BigInt?t=>BigInt(t):t=>t,Os=(xs("0x00"),xs("0xFFFFFFFFFFFFFFFF"),xs("0xFE3BFFFF"),xs("0x003007FF")),Rs=(xs("0x0003F800"),xs("0x1"),xs("0x2"),xs("0x4"),xs("0x8"),xs("0x10"),xs("0x20"),xs("0x40"),xs("0x80"),xs("0x100"),xs("0x200"),xs("0x400"),xs("0x800"),xs("0x1000"),xs("0x2000"),xs("0x4000"),xs("0x8000"),xs("0x10000"),xs("0x20000"),xs("0x00040000"),xs("0x01000000"),xs("0x02000000"),xs("0x04000000")),As=xs("0x08000000");xs("0x10000000"),xs("0x20000000"),xs("0x40000000"),xs("0x00080000"),xs("0x80000000"),xs("0x100000"),xs("0x200000"),xs("0x400000"),xs("0x800000"),xs("0x1000000000"),xs("0x3F0000000000000"),xs("0x100000000"),xs("0x10000000000000"),xs("0x20000000000000"),xs("0x40000000000000"),xs("0x80000000000000"),xs("0x100000000000000"),xs("0x200000000000000"),xs("0x200000000"),xs("0x400000000"),xs("0x800000000"),xs("0xC00000000"),xs("0x2000000000"),xs("0x4000000000");class Ds extends ht{static set _onLog(t){ni(Ds,is,t,"f",ns),Vr._onLog=t,bs._onLog=t}static get _onLog(){return ii(Ds,is,"f",ns)}static async detectEnvironment(){return await(async()=>({wasm:ri,worker:si,getUserMedia:oi,camera:await ai(),browser:ti.browser,version:ti.version,OS:ti.OS}))()}static async testCameraAccess(){const t=await Vr.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 Br))throw new TypeError("Invalid view.");if(!Ds._isRTU&&(null===(e=Vt.license)||void 0===e?void 0:e.LicenseManager)){if(!(null===(i=Vt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await Ht.loadWasm(),await Vt.license.dynamsoft()}const n=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)),n}get isEnableMirroring(){return this._isEnableMirroring}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");ni(this,as,t,"f")}get singleFrameMode(){return ii(this,as,"f")}get _isFetchingStarted(){return ii(this,fs,"f")}get disposed(){return ii(this,vs,"f")}constructor(t){if(super(),es.add(this),rs.set(this,"closed"),ss.set(this,void 0),os.set(this,void 0),this._isEnableMirroring=!1,this.isTorchOn=void 0,as.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},hs.set(this,(t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},o=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&o>this.canvasSizeLimit){const t=this.canvasSizeLimit/o;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const a=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?mi.GREY:mi.RGBA});let h=null;if(a){const t=Date.now();let o;o=a.pixelFormat===mi.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:Is.get(a.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:a.width,currentHeight:a.height,timeSpent:t-r,timeStamp:t},toCanvas:ii(this,ls,"f"),isDCEFrame:!0}}return h}),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():qi.convert(ii(this,us,"f"),t.width,t.height,this.cameraView),e||(e={x:0,y:0,width:t.width,height:t.height});const i=ii(this,hs,"f").call(this,t,t.width,t.height,e);ii(this,ss,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ls.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===_.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ti.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",()=>{ii(this,_s,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("camera:changed",()=>{this.clearBuffer()}),this._on("before:resolution:change",()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())}),this._on("resolution:changed",()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})}),this._on("paused",()=>{ii(this,_s,"f").stopCharging();const t=this.cameraView;t&&t.disposed}),this._on("resumed",()=>{const t=this.cameraView;t&&t.disposed}),this._on("tapfocus",()=>{ii(this,ms,"f").tapToFocus&&ii(this,_s,"f").startCharging()}),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;const o=t.intermediateResultUnits;if(ii(this,es,"m",ys).call(this)||!this.isOpen()||this.isPaused()||o[0]&&!o[0].originalImageTag)return;Ds._onLog&&(Ds._onLog("intermediateResultUnits:"),Ds._onLog(o));let a=!1,h=!1;for(let t of o){if(t.unitType===Et.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){a=!0;break}t.unitType===Et.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(h=!0)}if(Ds._onLog&&(Ds._onLog("hasLocalizedBarcodes:"),Ds._onLog(h)),ii(this,ms,"f").autoZoom||ii(this,ms,"f").enhancedFocus)if(a)ii(this,ps,"f").autoZoomInFrameArray.length=0,ii(this,ps,"f").autoZoomOutFrameCount=0,ii(this,ps,"f").frameArrayInIdealZoom.length=0,ii(this,ps,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),ii(this,ms,"f").autoZoom&&ii(this,_s,"f").startCharging()},a=async t=>{await this.setFocus(t),ii(this,ms,"f").enhancedFocus&&ii(this,_s,"f").startCharging()};if(h){const h=o[0].originalImageTag,l=(null===(i=h.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=h.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=h.cropRegion)||void 0===r?void 0:r.right)?h.cropRegion.right-l:h.originalWidth,d=(null===(s=h.cropRegion)||void 0===s?void 0:s.bottom)?h.cropRegion.bottom-c:h.originalHeight,f=h.currentWidth,g=h.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-ii(this,ps,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+ii(this,ps,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-ii(this,ps,"f").autoZoomDetectionArea)/2,o=s,a=this.video.videoHeight*(1+ii(this,ps,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:o},{x:i,y:a},{x:n,y:a}]}Ds._onLog&&(Ds._onLog("detectionArea:"),Ds._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Qi(a.y-i)>0&&Qi(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(tn([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||tn([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||tn([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||tn([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of o)if(e.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach(t=>{Br._transformCoordinates(t,l,c,u,d,f,g)}),t(r,e)&&s.push(i)}if(Ds._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Lr.createDrawingStyle({strokeStyle:"red"}));for(let i of o)if(i.unitType===Et.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new ki({points:i},e);t.addDrawingItems([r])}}}if(Ds._onLog&&(Ds._onLog("intersectedResults:"),Ds._onLog(s)),!s.length)return;let a;if(s.length){let t=s.filter(t=>t.possibleFormats==Rs||t.possibleFormats==As);if(t.length||(t=s.filter(t=>t.possibleFormats==Os),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};a=t[0];let i=e(a);if(1!=t.length)for(let n=1;n1.1*a.confidence||t[n].confidence>.9*a.confidence&&ri&&s>i&&o>i&&h>i&&m.result.moduleSize{}),ii(this,ps,"f").autoZoomInFrameArray.filter(t=>!0===t).length>=ii(this,ps,"f").autoZoomInFrameLimit[1]){ii(this,ps,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-o),(.5-n)/(.5-h)].filter(t=>t>0),a=Math.min(...i,ii(this,ps,"f").autoZoomInIdealModuleSize/m.result.moduleSize),l=this.getZoomSettings().factor;let c=Math.max(Math.pow(l*a,1/ii(this,ps,"f").autoZoomInMaxTimes),ii(this,ps,"f").autoZoomInMinStep);c=Math.min(c,a);let u=l*c;u=Math.max(ii(this,ps,"f").minValue,u),u=Math.min(ii(this,ps,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(ii(this,ps,"f").autoZoomInFrameArray.length=0,ii(this,ps,"f").frameArrayInIdealZoom.push(!0),ii(this,ps,"f").frameArrayInIdealZoom.splice(0,ii(this,ps,"f").frameArrayInIdealZoom.length-ii(this,ps,"f").frameLimitInIdealZoom[0]),ii(this,ps,"f").frameArrayInIdealZoom.filter(t=>!0===t).length>=ii(this,ps,"f").frameLimitInIdealZoom[1]&&(ii(this,ps,"f").frameArrayInIdealZoom.length=0,ii(this,ms,"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(!ii(this,ms,"f").autoZoom&&ii(this,ms,"f").enhancedFocus&&(ii(this,ps,"f").autoFocusFrameArray.push(!0),ii(this,ps,"f").autoFocusFrameArray.splice(0,ii(this,ps,"f").autoFocusFrameArray.length-ii(this,ps,"f").autoFocusFrameLimit[0]),ii(this,ps,"f").autoFocusFrameArray.filter(t=>!0===t).length>=ii(this,ps,"f").autoFocusFrameLimit[1])){ii(this,ps,"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(ii(this,ms,"f").autoZoom){if(ii(this,ps,"f").autoZoomInFrameArray.push(!1),ii(this,ps,"f").autoZoomInFrameArray.splice(0,ii(this,ps,"f").autoZoomInFrameArray.length-ii(this,ps,"f").autoZoomInFrameLimit[0]),ii(this,ps,"f").autoZoomOutFrameCount++,ii(this,ps,"f").frameArrayInIdealZoom.push(!1),ii(this,ps,"f").frameArrayInIdealZoom.splice(0,ii(this,ps,"f").frameArrayInIdealZoom.length-ii(this,ps,"f").frameLimitInIdealZoom[0]),ii(this,ps,"f").autoZoomOutFrameCount>=ii(this,ps,"f").autoZoomOutFrameLimit){ii(this,ps,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*ii(this,ps,"f").autoZoomOutStepRate,ii(this,ps,"f").autoZoomOutMinStep);n=Math.max(ii(this,ps,"f").minValue,n),n=Math.min(ii(this,ps,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}ii(this,ms,"f").enhancedFocus&&a({mode:"continuous"}).catch(()=>{})}!ii(this,ms,"f").autoZoom&&ii(this,ms,"f").enhancedFocus&&(ii(this,ps,"f").autoFocusFrameArray.length=0,a({mode:"continuous"}).catch(()=>{}))}}},ni(this,_s,new bs(1e4),"f"),this.getColourChannelUsageType()===p.CCUT_AUTO&&this.setColourChannelUsageType(p.CCUT_Y_CHANNEL_ONLY),this.setPixelFormat(_.IPF_GRAYSCALED)}setCameraView(t){if(!(t instanceof Br))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),ii(this,es,"m",ys).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;ii(this,es,"m",ys).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return ii(this,es,"m",ys).call(this)?ii(this,rs,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");e&&(e._singleFrameMode=this.singleFrameMode,ii(this,es,"m",ys).call(this)?e._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(e.getVideoElement()),e._startLoading()));let i={width:0,height:0,deviceId:""};if(ii(this,es,"m",ys).call(this));else{try{await this.cameraManager.open(),ni(this,os,this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),"f")}catch(t){throw e&&e._stopLoading(),"NotFoundError"===t.name?new Error("No Camera Found: No camera devices were detected. Please ensure a camera is connected and recognized by your system."):"NotAllowedError"===t.name?new Error("No Camera Access: Camera access is blocked. Please check your browser settings or grant permission to use the camera."):t}const n=!this.cameraManager.videoSrc&&!!(null===(t=this.cameraManager.getCameraCapabilities())||void 0===t?void 0:t.torch);let r,s=e.getUIElement();if(s=s.shadowRoot||s,r=s.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=s.elTorchAuto=s.querySelector(".dce-mn-torch-auto"),e=s.elTorchOn=s.querySelector(".dce-mn-torch-on"),i=s.elTorchOff=s.querySelector(".dce-mn-torch-off");t&&(t.style.display=null==this.isTorchOn?"":"none",n||(t.style.filter="invert(1)",t.style.cursor="not-allowed")),e&&(e.style.display=1==this.isTorchOn?"":"none"),i&&(i.style.display=0==this.isTorchOn?"":"none");let o=s.elBeepOn=s.querySelector(".dce-mn-beep-on"),a=s.elBeepOff=s.querySelector(".dce-mn-beep-off");o&&(o.style.display=Ts.allowBeep?"":"none"),a&&(a.style.display=Ts.allowBeep?"none":"");let h=s.elVibrateOn=s.querySelector(".dce-mn-vibrate-on"),l=s.elVibrateOff=s.querySelector(".dce-mn-vibrate-off");h&&(h.style.display=Ts.allowVibrate?"":"none"),l&&(l.style.display=Ts.allowVibrate?"none":""),s.elResolutionBox=s.querySelector(".dce-mn-resolution-box");let c,u=s.elZoom=s.querySelector(".dce-mn-zoom");u&&(u.style.display="none",c=s.elZoomSpan=u.querySelector("span"));let d=s.elToast=s.querySelector(".dce-mn-toast"),f=s.elCameraClose=s.querySelector(".dce-mn-camera-close"),g=s.elTakePhoto=s.querySelector(".dce-mn-take-photo"),m=s.elCameraSwitch=s.querySelector(".dce-mn-camera-switch"),p=s.elCameraAndResolutionSettings=s.querySelector(".dce-mn-camera-and-resolution-settings");p&&(p.style.display="none");const _=s.dceMnFs={},v=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",v);const y=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",y);const w=()=>{this.turnAutoTorch()};null==i||i.addEventListener("pointerdown",w);const C=()=>{Ts.allowBeep=!Ts.allowBeep,o&&(o.style.display=Ts.allowBeep?"":"none"),a&&(a.style.display=Ts.allowBeep?"none":"")};for(let t of[a,o])null==t||t.addEventListener("pointerdown",C);const E=()=>{Ts.allowVibrate=!Ts.allowVibrate,h&&(h.style.display=Ts.allowVibrate?"":"none"),l&&(l.style.display=Ts.allowVibrate?"none":"")};for(let t of[l,h])null==t||t.addEventListener("pointerdown",E);const S=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&I(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?p&&(p.style.display=p.style.display?"":"none"):p&&""===p.style.display&&(p.style.display="none"))};s.addEventListener("click",S);let b=null;_.funcInfoZoomChange=(t,e=3e3)=>{u&&c&&(c.textContent=t.toFixed(1),u.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout(()=>{u.style.display="none",b=null},e))};let T=null,I=_.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout(()=>{d.style.display="none",T=null},e))};const x=()=>{this.close()};null==f||f.addEventListener("click",x);const O=()=>{};null==g||g.addEventListener("pointerdown",O);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),o=null==s?void 0:s.indexOf("front");-1===o&&(o=null==s?void 0:s.indexOf("前"));let a=null==s?void 0:s.indexOf("back");if(-1===a&&(a=null==s?void 0:s.indexOf("后")),"number"==typeof o&&-1!==o?i=!0:"number"==typeof a&&-1!==a&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),!i){let t=this.cameraView.getUIElement();t=t.shadowRoot||t,t.elTorchAuto&&(t.elTorchAuto.style.display="none"),t.elTorchOn&&(t.elTorchOn.style.display="none"),t.elTorchOff&&(t.elTorchOff.style.display="")}n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==m||m.addEventListener("pointerdown",R);let A=-1/0,D=1;const L=t=>{let e=Date.now();e-A>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),A=e};r.addEventListener("wheel",L);const M=new Map;let F=!1;const P=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=M.get(i.identifier),s=M.get(n.identifier);if(!r||!s)break;let o=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),a=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),h=Date.now();if(F||h-A<100)return;h-A>1e3&&(D=this.getZoomSettings().factor),D*=a/o,D>20&&(D=20),D<1&&(D=1);let l=!1;"safari"==(null===(e=null==ti?void 0:ti.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(a/o>1&&D<2?(D=2,l=!0):a/o<1&&D<2&&(D=1,l=!0)),F=!0,l&&I("zooming..."),await this.setZoom({factor:D}),l&&(d.textContent=""),F=!1,A=Date.now();break}M.clear();for(let e of t.touches)M.set(e.identifier,{x:e.clientX,y:e.clientY})};s.addEventListener("touchstart",P),s.addEventListener("touchmove",P),s.addEventListener("touchend",P),s.addEventListener("touchcancel",P),_.unbind=()=>{null==t||t.removeEventListener("pointerdown",v),null==e||e.removeEventListener("pointerdown",y),null==i||i.removeEventListener("pointerdown",w);for(let t of[a,o])null==t||t.removeEventListener("pointerdown",C);for(let t of[l,h])null==t||t.removeEventListener("pointerdown",E);s.removeEventListener("click",S),null==f||f.removeEventListener("click",x),null==g||g.removeEventListener("pointerdown",O),null==m||m.removeEventListener("pointerdown",R),r.removeEventListener("wheel",L),s.removeEventListener("touchstart",P),s.removeEventListener("touchmove",P),s.removeEventListener("touchend",P),s.removeEventListener("touchcancel",P),delete s.dceMnFs,r.style.display="none"},r.style.display="",t&&null==this.isTorchOn&&setTimeout(()=>{this.turnAutoTorch(1e3)},0)}this.isTorchOn&&this.turnOnTorch().catch(()=>{});const o=this.getResolution();i.width=o.width,i.height=o.height,i.deviceId=this.getSelectedCamera().deviceId}return ni(this,rs,"open","f"),e&&(e._innerComponent.style.display="",ii(this,es,"m",ys).call(this)||(e._stopLoading(),e._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),e._renderResolutionInfo({width:i.width,height:i.height}),e.eventHandler.fire("content:updated",null,{async:!1}),e.eventHandler.fire("videoEl:resized",null,{async:!1}))),this.toggleMirroring(this._isEnableMirroring),ii(this,ss,"f").fire("opened",null,{target:this,async:!1}),this.cameraManager._zoomPreSetting&&(await this.setZoom(this.cameraManager._zoomPreSetting),this.cameraManager._zoomPreSetting=null),i}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),ii(this,es,"m",ys).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}ni(this,rs,"closed","f"),ii(this,_s,"f").stopCharging(),e&&(e._innerComponent.style.display="none",ii(this,es,"m",ys).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),ii(this,ss,"f").fire("closed",null,{target:this,async:!1})}pause(){if(ii(this,es,"m",ys).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!ii(this,es,"m",ys).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(ii(this,es,"m",ys).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){var e;if(!t)throw new Error("Invalid value.");let i;i="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(i),this.isTorchOn=!1;const n=this.getResolution(),r=this.cameraView;if(r&&!r.disposed&&(r._stopLoading(),r._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),r._renderResolutionInfo({width:n.width,height:n.height})),this.isOpen()){const t=!!(null===(e=this.cameraManager.getCameraCapabilities())||void 0===e?void 0:e.torch);let i=r.getUIElement();if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let e=i.elTorchAuto=i.querySelector(".dce-mn-torch-auto");e&&(t?(e.style.filter="none",e.style.cursor="pointer"):(e.style.filter="invert(1)",e.style.cursor="not-allowed"))}}return this.toggleMirroring(this._isEnableMirroring),{width:n.width,height:n.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch(()=>{});const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),this.toggleMirroring(this._isEnableMirroring),ii(this,us,"f")&&this.setScanRegion(ii(this,us,"f")),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ii(this,ss,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?ii(this,ss,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(ii(this,es,"m",ys).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(ii(this,es,"m",ys).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){var e;const i=this.isOpen()&&!this.cameraManager.videoSrc?this.cameraManager.getCameraCapabilities():{};if(!(null==i?void 0:i.torch)){let t=this.cameraView.getUIElement();return t=t.shadowRoot||t,void(null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"))}if(null!=this._taskid4AutoTorch){if(!(t{var t,e,i;if(this.disposed||n||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++s>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let o;try{o=this.fetchImage()}catch(t){}if(!o||!o.width||!o.height)return;let a=0;if(_.IPF_GRAYSCALED===o.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Ds._onLog)||void 0===t||t.call(Ds,`darkCount ${r}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(e=null==t?void 0:t.dceMnFs)||void 0===e||e.funcShowToast("Torch Auto On")}catch(t){console.warn(t),n=!0;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,null===(i=null==e?void 0:e.dceMnFs)||void 0===i||i.funcShowToast("Torch Not Supported")}}}else r=0};this._taskid4AutoTorch=setInterval(o,t),this.isTorchOn=void 0,o();let a=this.cameraView.getUIElement();a=a.shadowRoot||a,a.elTorchAuto&&(a.elTorchAuto.style.display=""),a.elTorchOn&&(a.elTorchOn.style.display="none"),a.elTorchOff&&(a.elTorchOff.style.display="none")}async setColorTemperature(t){if(ii(this,es,"m",ys).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(ii(this,es,"m",ys).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(ii(this,es,"m",ys).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(ii(this,es,"m",ys).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(ii(this,es,"m",ys).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(ii(this,es,"m",ys).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){ii(this,ps,"f").minValue=t.min,ii(this,ps,"f").maxValue=t.max}getAutoZoomRange(){return{min:ii(this,ps,"f").minValue,max:ii(this,ps,"f").maxValue}}enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=Vt.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&gi.EF_ENHANCED_FOCUS&&(ii(this,ms,"f").enhancedFocus=!0),t&gi.EF_AUTO_ZOOM&&(ii(this,ms,"f").autoZoom=!0),t&gi.EF_TAP_TO_FOCUS&&(ii(this,ms,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&gi.EF_ENHANCED_FOCUS&&(ii(this,ms,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch(()=>{})),t&gi.EF_AUTO_ZOOM&&(ii(this,ms,"f").autoZoom=!1,this.resetZoom().catch(()=>{})),t&gi.EF_TAP_TO_FOCUS&&(ii(this,ms,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),ii(this,es,"m",Cs).call(this)&&ii(this,es,"m",ws).call(this)||ii(this,_s,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!D(t)&&!N(t))throw TypeError("Invalid 'region'.");ni(this,us,t?JSON.parse(JSON.stringify(t)):null,"f"),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(ii(this,us,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");ni(this,cs,t,"f")}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||ii(this,es,"m",ys).call(this))}startFetching(){if(ii(this,es,"m",ys).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");ii(this,fs,"f")||(ni(this,fs,!0,"f"),ii(this,es,"m",Es).call(this))}stopFetching(){ii(this,fs,"f")&&(Ds._onLog&&Ds._onLog("DCE: stop fetching loop: "+Date.now()),ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),ni(this,fs,!1,"f"))}toggleMirroring(t){this.isOpen()&&(this.video.style.transform=`scaleX(${t?"-1":"1"})`),this._isEnableMirroring=t}fetchImage(t=!1){if(ii(this,es,"m",ys).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(!this.cameraManager.isVideoLoaded())throw new Error("The video is not loaded.");const e=this.getResolution();if(!(null==e?void 0:e.width)||!(null==e?void 0:e.height))throw new Error("The video is not loaded.");let i,n;if(i=qi.convert(ii(this,us,"f"),e.width,e.height,this.cameraView),i||(i={x:0,y:0,width:e.width,height:e.height}),i.x>e.width||i.y>e.height)throw new Error("Invalid scan region.");if(i.x+i.width>e.width&&(i.width=e.width-i.x),i.y+i.height>e.height&&(i.height=e.height-i.y),ii(this,us,"f")&&!t)n={sx:i.x,sy:i.y,sWidth:i.width,sHeight:i.height,dWidth:i.width,dHeight:i.height};else{const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});n={sx:t.x,sy:t.y,sWidth:t.width,sHeight:t.height,dWidth:t.width,dHeight:t.height}}const r=Math.max(n.dWidth,n.dHeight);if(this.canvasSizeLimit&&r>this.canvasSizeLimit){const t=this.canvasSizeLimit/r;n.dWidth>n.dHeight?(n.dWidth=this.canvasSizeLimit,n.dHeight=Math.round(n.dHeight*t)):(n.dWidth=Math.round(n.dWidth*t),n.dHeight=this.canvasSizeLimit)}const s=this.cameraManager.getFrameData({position:n,pixelFormat:this.getPixelFormat()===_.IPF_GRAYSCALED?mi.GREY:mi.RGBA,isEnableMirroring:this._isEnableMirroring});if(!s)return null;let o;o=s.pixelFormat===mi.GREY?s.width:4*s.width;let a=!0;return 0===n.sx&&0===n.sy&&n.sWidth===e.width&&n.sHeight===e.height&&(a=!1),{bytes:s.data,width:s.width,height:s.height,stride:o,format:Is.get(s.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:vt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:n.sx,top:n.sy,right:n.sx+n.sWidth,bottom:n.sy+n.sHeight,isMeasuredInPercentage:!1},originalWidth:e.width,originalHeight:e.height,currentWidth:s.width,currentHeight:s.height,timeSpent:s.timeSpent,timeStamp:s.timeStamp},toCanvas:ii(this,ls,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,ii(this,fs,"f")&&(ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),ni(this,gs,setTimeout(()=>{this.disposed||ii(this,es,"m",Es).call(this)},t),"f"))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){ni(this,ds,t,"f")}getPixelFormat(){return ii(this,ds,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(ii(this,es,"m",ys).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",()=>{t&&this.open(),e.remove()},{once:!0})}),e.addEventListener("change",async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let o=qi.convert(ii(this,us,"f"),r,s,this.cameraView);o||(o={x:0,y:0,width:r,height:s});const a=ii(this,hs,"f").call(this,n,r,s,o);t&&t(a)}),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=this.convertToContainCoordinates(t),i=ii(this,es,"m",Ss).call(this,e);return{x:i.pageX,y:i.pageY}}convertToClientCoordinates(t){const e=this.convertToContainCoordinates(t),i=ii(this,es,"m",Ss).call(this,e);return{x:i.clientX,y:i.clientY}}convertToScanRegionCoordinates(t){if(!ii(this,us,"f"))return JSON.parse(JSON.stringify(t));const e=this.convertToContainCoordinates(t);if(this.isOpen()){const t=this.cameraView.getVisibleRegionOfVideo({inPixels:!0});ni(this,os,t||ii(this,os,"f"),"f")}let i,n,r=ii(this,us,"f").left||ii(this,us,"f").x||0,s=ii(this,us,"f").top||ii(this,us,"f").y||0;if(!ii(this,us,"f").isMeasuredInPercentage)return{x:e.x-(r+ii(this,os,"f").x),y:e.y-(s+ii(this,os,"f").y)};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ii(this,es,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ii(this,es,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(ii(this,es,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");i=t.width,n=t.height}else i=ii(this,os,"f").width,n=ii(this,os,"f").height;return{x:e.x-(Math.round(r*i/100)+ii(this,os,"f").x),y:e.y-(Math.round(s*n/100)+ii(this,os,"f").y)}}convertToContainCoordinates(t){if("contain"===this.cameraView.getVideoFit())return t;const e=this.cameraView.getVisibleRegionOfVideo({inPixels:!0}),i=JSON.parse(JSON.stringify(t));return D(ii(this,us,"f"))?ii(this,us,"f").isMeasuredInPercentage?(i.x=e.width*(ii(this,us,"f").left/100)+e.x+t.x,i.y=e.height*(ii(this,us,"f").top/100)+e.y+t.y):(i.x=ii(this,us,"f").left+e.x+t.x,i.y=ii(this,us,"f").top+e.y+t.y):ii(this,us,"f").isMeasuredInPercentage?(i.x=e.width*(ii(this,us,"f").x/100)+e.x+t.x,i.y=e.height*(ii(this,us,"f").y/100)+e.y+t.y):(i.x=ii(this,us,"f").x+e.x+t.x,i.y=ii(this,us,"f").y+e.y+t.y),i}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),ni(this,vs,!0,"f")}}var Ls,Ms,Fs,Ps,ks,Ns,Bs,js;is=Ds,rs=new WeakMap,ss=new WeakMap,os=new WeakMap,as=new WeakMap,hs=new WeakMap,ls=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,es=new WeakSet,ys=function(){return"disabled"!==this.singleFrameMode},ws=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Cs=function(){for(let t in ii(this,ms,"f"))if(1==ii(this,ms,"f")[t])return!0;return!1},Es=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!ii(this,fs,"f"))return ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),void ni(this,gs,setTimeout(()=>{this.disposed||ii(this,es,"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=ii(this,cs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout(()=>{var t;null===(t=ii(this,cs,"f"))||void 0===t||t.onErrorReceived(mt.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()),ii(this,ss,"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 m.BOPM_BLOCK:break;case m.BOPM_UPDATE:e()}else e();ii(this,gs,"f")&&clearTimeout(ii(this,gs,"f")),ni(this,gs,setTimeout(()=>{this.disposed||ii(this,es,"m",t).call(this)},this.fetchInterval),"f")},Ss=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!ii(this,es,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(ii(this,es,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:o,height:a}=this.cameraView._innerComponent.getBoundingClientRect();if(o<=0||a<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let h,l,c;if(ii(this,es,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");h=t.width,l=t.height,c="contain"}else{const t=this.getVideoEl();h=t.videoWidth,l=t.videoHeight,c=this.cameraView.getVideoFit()}const u=o/a,d=h/l;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(ii(this,Ps,"f")||ni(this,Ps,new Us,"f"),!ii(this,Ps,"f").magnifierCanvas)return;document.body.contains(ii(this,Ps,"f").magnifierCanvas)||(ii(this,Ps,"f").magnifierCanvas.style.position="fixed",ii(this,Ps,"f").magnifierCanvas.style.boxSizing="content-box",ii(this,Ps,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(ii(this,Ps,"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 ii(this,Ns,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,o=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];ii(this,Ps,"f").update(s,t.pointer,r,o);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(ii(this,Ps,"f").magnifierCanvas.style.left="auto",ii(this,Ps,"f").magnifierCanvas.style.top="0",ii(this,Ps,"f").magnifierCanvas.style.right="0"):(ii(this,Ps,"f").magnifierCanvas.style.left="0",ii(this,Ps,"f").magnifierCanvas.style.top="0",ii(this,Ps,"f").magnifierCanvas.style.right="auto")}ii(this,Ps,"f").show()}),Ns.set(this,()=>{ii(this,Ps,"f")&&ii(this,Ps,"f").hide()}),Bs.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await en(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(A(t)){ni(this,Fs,t,"f");const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===_.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Ys){if(!Gs&&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"./"}})(),Xs=t=>t&&"object"==typeof t&&"function"==typeof t.then,zs=(async()=>{})().constructor;let qs=class extends zs{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xs(t)?e=t:"function"==typeof t&&(e=new zs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(Xs(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Ks=" is not allowed to change after `createInstance` or `loadWasm` is called.",Zs=!Gs&&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"))||"",Js=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Ks);i._license=e}};!Gs&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const $s=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=$s(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Ks);i._licenseServer=e}},to=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Ks);i._deviceFriendlyName=e}};let eo,io,no,ro,so;"undefined"!=typeof navigator&&(eo=navigator,io=eo.userAgent,no=eo.platform,ro=eo.mediaDevices),function(){if(!Gs){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:eo.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:no,search:"Win"},Mac:{str:no},Linux:{str:no}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||io,o=r.search||e,a=r.verStr||io,h=r.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){n=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||io,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=io.indexOf("Windows NT")&&(r="HarmonyOS"),so={browser:i,version:n,OS:r}}Gs&&(so={browser:"ssr",version:0,OS:"ssr"})}(),ro&&ro.getUserMedia,"Chrome"===so.browser&&so.version>66||"Safari"===so.browser&&so.version>13||"OPR"===so.browser&&so.version>43||"Edge"===so.browser&&so.version;const oo=()=>(Ht.loadWasm(),Dt("dynamsoft_inited",async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=ho;if(i._pLoad.isEmpty){let n,r,s,o=i._license||"",a=JSON.parse(JSON.stringify(i._licenseServer)),h=i._sessionPassword,l=0;if(o.startsWith("t")||o.startsWith("f"))l=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))l=1;else{l=2;const e=o.indexOf(":");-1!=e&&(o=o.substring(e+1));const i=o.indexOf("?");if(-1!=i&&(r=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))l=0;else{if(o.startsWith("DLS2")){let e;try{let t=o.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(o=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),a=$s(t)}!h&&e.sessionPassword&&(h=e.sessionPassword),n=e.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(l=1)}}if(l&&(e||(Ws.crypto||(s="Please upgrade your browser to support online key."),Ws.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===l&&(o="",console.warn("Applying for a public trial license ...")),{lt:l,l:o,ls:a,sp:h,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Ks)})(),o=new qs;ho._pLoad.task=o,(async()=>{try{await ho._pLoad}catch(t){}})();let a=Ft();Pt[a]=e=>{if(e.message&&ho._onAuthMessage){let t=ho._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(kt&&kt("init license success"),e.message&&console.warn(e.message),Ht._bSupportIRTModule=e.bSupportIRTModule,Ht._bSupportDce4Module=e.bSupportDce4Module,ho.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):o.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=V(Ht.engineResourcePaths),i=("DCV"===Ht._bundleEnv?t.dcvData:t.dbrBundle)+"ui/";(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.insertAdjacentHTML("beforeend",r);let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}});else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",()=>{a.remove();for(let t of o)t.remove()});else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,n);o.innerText=a;let h=e.substring(r+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:ho._bNeverShowDialog,engineResourcePath:i,_onLog:kt},e.success?"warn":"error",e.message)}e.success?o.resolve(void 0):o.reject(i)},await At("core");const h=await Ht.getModuleVersion();Lt.postMessage({type:"license_dynamsoft",body:{v:"DCV"===Ht._bundleEnv?h.CVR.replace(/\.\d+$/,""):h.DBR.replace(/\.\d+$/,""),brtk:!!t,bptk:1===t,l:e,os:so,fn:ho.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:a}),ho.bCallInitLicense=!0,await o}));let ao;Vt.license={},Vt.license.dynamsoft=oo,Vt.license.getAR=async()=>{{let t=Rt.dynamsoft_inited;t&&t.isRejected&&await t}return Lt?new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success){delete i.success;{let t=ho.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)}},Lt.postMessage({type:"license_getAR",id:i})}):null};let ho=class t{static setLicenseServer(e){Qs(t,e)}static get license(){return this._license}static set license(e){Js(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Qs(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){to(t,e)}static initLicense(e,i){if(Js(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return oo()}static setDeviceFriendlyName(e){to(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await Dt("dynamsoft_uuid",async()=>{await Ht.loadWasm();let t=new qs,e=Ft();Pt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},Lt.postMessage({type:"license_getDeviceUUID",id:e}),ao=await t}),ao))()}};ho._pLoad=new qs,ho.bPassValidation=!1,ho.bCallInitLicense=!1,ho._license=Zs,ho._licenseServer=[],ho._deviceFriendlyName="",Ht.engineResourcePaths.license={version:"4.2.20-dev-20251029130543",path:Hs,isInternal:!0},Gt.license={wasm:!0,js:!0},Vt.license.LicenseManager=ho;const lo="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,lo)<0&&(Ht.engineResourcePaths.std={version:lo,path:(t=>{if(null==t&&(t="./"),Gs||Ys);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Hs+`../../dynamsoft-capture-vision-std@${lo}/dist/`),isInternal:!0});let co=class{static getVersion(){return`4.2.20-dev-20251029130543(Worker: ${Ut.license&&Ut.license.worker||"Not Loaded"}, Wasm: ${Ut.license&&Ut.license.wasm||"Not Loaded"})`}};const uo=()=>window.matchMedia("(orientation: landscape)").matches,fo=t=>Object.prototype.toString.call(t).slice(8,-1);function go(t,e){for(const i in e)"Object"===fo(e[i])&&i in t?go(t[i],e[i]):t[i]=e[i];return t}function mo(t){const e=t.label.toLowerCase();return["front","user","selfie","前置","前摄","自拍","前面","インカメラ","フロント","전면","셀카","фронтальная","передняя","frontal","delantera","selfi","frontal","frente","avant","frontal","caméra frontale","vorder","vorderseite","frontkamera","anteriore","frontale","amamiya","al-amam","مقدمة","أمامية","aage","आगे","फ्रंट","सेल्फी","ด้านหน้า","กล้องหน้า","trước","mặt trước","ön","ön kamera","depan","kamera depan","przednia","přední","voorkant","voorzijde","față","frontală","εμπρός","πρόσθια","קדמית","קדמי","selfcamera","facecam","facetime"].some(t=>e.includes(t))}function po(t){if("object"!=typeof t||null===t)return t;let e;if(Array.isArray(t)){e=[];for(let i=0;ie.endsWith(t)))return!1;return!!t.type.startsWith("image/")}const vo="undefined"==typeof self,yo="function"==typeof importScripts,wo=(()=>{if(!yo){if(!vo&&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"./"}})(),Co=t=>{if(null==t&&(t="./"),vo||yo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Ht.engineResourcePaths.utility={version:"2.2.20-dev-20251029130550",path:wo,isInternal:!0},Gt.utility={js:!0,wasm:!0};const Eo="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,Eo)<0&&(Ht.engineResourcePaths.std={version:Eo,path:Co(wo+`../../dynamsoft-capture-vision-std@${Eo}/dist/`),isInternal:!0});const So="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,So)<0)&&(Ht.engineResourcePaths.dip={version:So,path:Co(wo+`../../dynamsoft-image-processing@${So}/dist/`),isInternal:!0});let bo=class{static getVersion(){return`2.2.20-dev-20251029130550(Worker: ${Ut.utility&&Ut.utility.worker||"Not Loaded"}, Wasm: ${Ut.utility&&Ut.utility.wasm||"Not Loaded"})`}};function To(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}"function"==typeof SuppressedError&&SuppressedError;const Io="undefined"==typeof self,xo="function"==typeof importScripts,Oo=(()=>{if(!xo){if(!Io&&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"./"}})(),Ro=t=>{if(null==t&&(t="./"),Io||xo);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Ht.engineResourcePaths.dbr={version:"11.0.30-dev-20250522174049",path:Oo,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const Ao="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,Ao)<0&&(Ht.engineResourcePaths.std={version:Ao,path:Ro(Oo+`../../dynamsoft-capture-vision-std@${Ao}/dist/`),isInternal:!0});const Do="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,Do)<0)&&(Ht.engineResourcePaths.dip={version:Do,path:Ro(Oo+`../../dynamsoft-image-processing@${Do}/dist/`),isInternal:!0});const Lo={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var Mo,Fo,Po,ko,No;(No=Mo||(Mo={}))[No.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",No[No.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",No[No.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT",function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Fo||(Fo={})),function(t){t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=4294967295]="LM_END"}(Po||(Po={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=4294967295]="DM_END"}(ko||(ko={}));const Bo=async t=>{let e;await new Promise((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)});const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:_.IPF_ABGR_8888}};function jo(t,e){let i=!0;for(let o=0;o1)return Math.sqrt((h-o)**2+(l-a)**2);{const t=r+u*(o-r),e=s+u*(a-s);return Math.sqrt((h-t)**2+(l-e)**2)}}function Go(t){const e=[];for(let i=0;i=0&&h<=1&&l>=0&&l<=1?{x:t.x+l*r,y:t.y+l*s}:null}function Ho(t){let e=0;for(let i=0;i0}function zo(t,e){for(let i=0;i<4;i++)if(!Xo(t.points[i],t.points[(i+1)%4],e))return!1;return!0}function qo(t,e,i,n){const r=t.points,s=e.points;let o=8*i;o=Math.max(o,5);const a=Go(r)[3],h=Go(r)[1],l=Go(s)[3],c=Go(s)[1];let u,d=0;if(u=Math.max(Math.abs(Vo(a,e.points[0])),Math.abs(Vo(a,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Vo(h,e.points[1])),Math.abs(Vo(h,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Vo(l,t.points[0])),Math.abs(Vo(l,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Vo(c,t.points[1])),Math.abs(Vo(c,t.points[2]))),u>d&&(d=u),d>o)return!1;const f=Wo(Go(r)[0]),g=Wo(Go(r)[2]),m=Wo(Go(s)[0]),p=Wo(Go(s)[2]),_=Uo(f,p),v=Uo(m,g),y=_>v,w=Math.min(_,v),C=Uo(f,g),E=Uo(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i}),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),o=0,a=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,o+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,a+=s[t];o/=4,a/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1;if(Math.abs(s[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1}return e.x=o,e.y=a,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(zo(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(zo(this.location,e))return!0}else{for(let e=0;e<4;e++)if(zo(t,this.location.points[e]))return!0;if(zo(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Vo(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Yo(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach(t=>{jo(e,t)&&i.push(t)}),e.forEach(e=>{jo(t,e)&&i.push(e)}),Ho(function(t){if(t.length<=1)return t;t.sort((t,e)=>t.x-e.x||t.y-e.y);const e=t.shift();return t.sort((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x)),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}var Zo,Jo,$o,Qo,ta;const ea={barcode:2,text_line:4,detected_quad:8,deskewed_image:16,enhanced_image:64},ia=t=>Object.values(ea).includes(t)||ea.hasOwnProperty(t),na=(t,e)=>"string"==typeof t?e[ea[t]]:e[t],ra=(t,e,i)=>{"string"==typeof t?e[ea[t]]=i:e[t]=i},sa=(t,e,i)=>{const n=[{type:ft.CRIT_BARCODE,resultName:"decodedBarcodesResult",itemNames:["barcodeResultItems"]},{type:ft.CRIT_TEXT_LINE,resultName:"recognizedTextLinesResult",itemNames:["textLineResultItems"]}],r=e.items;if(t.isResultCrossVerificationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type!==i||r[t].verified||r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&t.verified)})}if(t.isResultDeduplicationEnabled(i)){for(let t=r.length-1;t>=0;t--)r[t].type===i&&r[t].duplicate&&r.splice(t,1);const t=n.filter(t=>t.type===i)[0];e[t.resultName]&&t.itemNames.forEach(n=>{const r=e[t.resultName][n];e[t.resultName][n]=r.filter(t=>t.type===i&&!t.duplicate)})}};class oa{constructor(){this.verificationEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!0,[ft.CRIT_DETECTED_QUAD]:!0,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1},this.duplicateFilterEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1,[ft.CRIT_ENHANCED_IMAGE]:!1},this.duplicateForgetTime={[ft.CRIT_BARCODE]:3e3,[ft.CRIT_TEXT_LINE]:3e3,[ft.CRIT_DETECTED_QUAD]:3e3,[ft.CRIT_DESKEWED_IMAGE]:3e3,[ft.CRIT_ENHANCED_IMAGE]:3e3},Zo.set(this,new Map),Jo.set(this,new Map),$o.set(this,new Map),Qo.set(this,new Map),ta.set(this,new Map),this.overlapSet=[],this.stabilityCount=0,this.crossVerificationFrames=5,this.latestOverlappingEnabled={[ft.CRIT_BARCODE]:!1,[ft.CRIT_TEXT_LINE]:!1,[ft.CRIT_DETECTED_QUAD]:!1,[ft.CRIT_DESKEWED_IMAGE]:!1},this.maxOverlappingFrames={[ft.CRIT_BARCODE]:this.crossVerificationFrames,[ft.CRIT_TEXT_LINE]:this.crossVerificationFrames,[ft.CRIT_DETECTED_QUAD]:this.crossVerificationFrames,[ft.CRIT_DESKEWED_IMAGE]:this.crossVerificationFrames},Object.defineProperties(this,{onOriginalImageResultReceived:{value:t=>{},writable:!1},onDecodedBarcodesReceived:{value:t=>{this.latestOverlappingFilter(t),sa(this,t,ft.CRIT_BARCODE)},writable:!1},onRecognizedTextLinesReceived:{value:t=>{sa(this,t,ft.CRIT_TEXT_LINE)},writable:!1},onProcessedDocumentResultReceived:{value:t=>{},writable:!1},onParsedResultsReceived:{value:t=>{},writable:!1}})}_dynamsoft(){To(this,Zo,"f").forEach((t,e)=>{ra(e,this.verificationEnabled,t)}),To(this,Jo,"f").forEach((t,e)=>{ra(e,this.duplicateFilterEnabled,t)}),To(this,$o,"f").forEach((t,e)=>{ra(e,this.duplicateForgetTime,t)}),To(this,Qo,"f").forEach((t,e)=>{ra(e,this.latestOverlappingEnabled,t)}),To(this,ta,"f").forEach((t,e)=>{ra(e,this.maxOverlappingFrames,t)})}enableResultCrossVerification(t,e){ia(t)&&To(this,Zo,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!ia(t)&&na(t,this.verificationEnabled)}enableResultDeduplication(t,e){ia(t)&&(e&&this.enableLatestOverlapping(t,!1),To(this,Jo,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!ia(t)&&na(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){ia(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),To(this,$o,"f").set(t,e))}getDuplicateForgetTime(t){return ia(t)?na(t,this.duplicateForgetTime):-1}getFilteredResultItemTypes(){let t=0;const e=[ft.CRIT_BARCODE,ft.CRIT_TEXT_LINE,ft.CRIT_DETECTED_QUAD,ft.CRIT_DESKEWED_IMAGE,ft.CRIT_ENHANCED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Lo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Lo.BF_GS1_DATABAR))!=BigInt(0);return new Ko(h,e?1:2,e,t)}}).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(l).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Lo.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Lo.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0))}f.sort((t,e)=>e-t).forEach((e,i)=>{t.items.splice(e,1)}),d.forEach(e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))})}}}var aa,ha,la,ca,ua,da,fa,ga,ma,pa,_a,va,ya,wa,Ca,Ea,Sa,ba,Ta,Ia,xa,Oa,Ra,Aa,Da,La,Ma,Fa,Pa,ka,Na,Ba,ja,Ua,Va,Ga;Zo=new WeakMap,Jo=new WeakMap,$o=new WeakMap,Qo=new WeakMap,ta=new WeakMap;class Wa{async readFromFile(t){return await Bo(t)}async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=X(t);return G(n,e,i)}async readFromMemory(t){if(!To(Wa,aa,"f",ha).has(t))throw new Error("Image data ID does not exist.");const{ptr:e,length:i}=To(Wa,aa,"f",ha).get(t);return await new Promise((t,n)=>{let r=Ft();Pt[r]=async e=>{if(e.success)return 0!==e.imageData.errorCode&&n(new Error(`[${e.imageData.errorCode}] ${e.imageData.errorString}`)),t(e.imageData);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},Lt.postMessage({type:"utility_readFromMemory",id:r,body:{ptr:e,length:i}})})}async saveToMemory(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{var i,n;if(e.success)return function(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");r?r.value=i:e.set(t,i)}(i=Wa,aa,(n=To(i,aa,"f",la),++n),0,la),To(Wa,aa,"f",ha).set(To(Wa,aa,"f",la),JSON.parse(e.memery)),t(To(Wa,aa,"f",la));{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToMemory",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}async readFromBase64String(t){return await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success)return 0!==t.imageData.errorCode&&i(new Error(`[${t.imageData.errorCode}] ${t.imageData.errorString}`)),e(t.imageData);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"utility_readFromBase64String",id:n,body:{base64String:t}})})}async saveToBase64String(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return 0!==e.base64Data.errorCode&&a(new Error(`[${e.base64Data.errorCode}] ${e.base64Data.errorString}`)),t(e.base64Data.base64String);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_saveToBase64String",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,fileFormat:e}})})}}aa=Wa,ha={value:new Map},la={value:0};class Ya{async drawOnImage(t,e,i,n=4294901760,r=1,s="test.png",o){if(!t)throw new Error("Invalid image.");if(!e)throw new Error("Invalid drawingItem.");if(!i)throw new Error("Invalid type.");let a;if(t instanceof Blob)a=await Bo(t);else if("string"==typeof t){let e=await B(t,"blob");a=await Bo(e)}else A(t)&&(a=t,"bigint"==typeof a.format&&(a.format=Number(a.format)));return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return o&&(new Wa).saveToFile(e.image,s,o),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:Array.isArray(e)?e:[e],color:n,thickness:r,type:i}})})}}class Ha{async cropImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropImage",id:h,body:{type:"Rect",bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}async adjustBrightness(t,e){if(e>100||e<-100)throw new Error("Invalid brightness, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustBrightness);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustBrightness",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,brightness:e}})})}async adjustContrast(t,e){if(e>100||e<-100)throw new Error("Invalid contrast, range: [-100, 100].");const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.adjustContrast);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_adjustContrast",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,contrast:e}})})}async filterImage(t,e){if(![0,1,2].includes(e))throw new Error("Invalid filterType.");const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.filterImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_filterImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,filterType:e}})})}async convertToGray(t,e,i,n){const{bytes:r,width:s,height:o,stride:a,format:h}=await Bo(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToGray);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToGray",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,R:e,G:i,B:n}})})}async convertToBinaryGlobal(t,e=-1,i=!1){const{bytes:n,width:r,height:s,stride:o,format:a}=await Bo(t);return await new Promise((t,h)=>{let l=Ft();Pt[l]=async e=>{if(e.success)return t(e.convertToBinaryGlobal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}},Lt.postMessage({type:"utility_convertToBinaryGlobal",id:l,body:{bytes:n,width:r,height:s,stride:o,format:a,threshold:e,invert:i}})})}async convertToBinaryLocal(t,e=0,i=0,n=!1){const{bytes:r,width:s,height:o,stride:a,format:h}=await Bo(t);return await new Promise((t,l)=>{let c=Ft();Pt[c]=async e=>{if(e.success)return t(e.convertToBinaryLocal);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l(t)}},Lt.postMessage({type:"utility_convertToBinaryLocal",id:c,body:{bytes:r,width:s,height:o,stride:a,format:h,blockSize:e,compensation:i,invert:n}})})}async cropAndDeskewImage(t,e){const{bytes:i,width:n,height:r,stride:s,format:o}=await Bo(t);return await new Promise((t,a)=>{let h=Ft();Pt[h]=async e=>{if(e.success)return t(e.cropAndDeskewImage);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}},Lt.postMessage({type:"utility_cropAndDeskewImage",id:h,body:{bytes:i,width:n,height:r,stride:s,format:o,roi:e}})})}}!function(t){t[t.FT_HIGH_PASS=0]="FT_HIGH_PASS",t[t.FT_SHARPEN=1]="FT_SHARPEN",t[t.FT_SMOOTH=2]="FT_SMOOTH"}(ca||(ca={}));class Xa{constructor(t){if(ua.add(this),ga.set(this,void 0),ma.set(this,{status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]}),pa.set(this,!1),_a.set(this,void 0),va.set(this,void 0),ya.set(this,void 0),wa.set(this,void 0),this.config=po(Xt),t&&"object"!=typeof t||Array.isArray(t))throw"Invalid config.";go(this.config,t),Ds._isRTU=!0}get disposed(){return e(this,pa,"f")}launch(){return t(this,void 0,void 0,function*(){if(e(this,pa,"f"))throw new Error("The BarcodeScanner instance has been destroyed.");if(e(Xa,da,"f",fa)&&!e(Xa,da,"f",fa).isFulfilled&&!e(Xa,da,"f",fa).isRejected)throw new Error("Cannot call `launch()` while a previous task is still running.");return i(Xa,da,new Kt,"f",fa),e(this,ua,"m",Ca).call(this),e(Xa,da,"f",fa)})}decode(n,r="ReadBarcodes_Default"){return t(this,void 0,void 0,function*(){i(this,va,r,"f"),yield e(this,ua,"m",Ea).call(this,!0),e(this,wa,"f")||i(this,wa,new oa,"f"),e(this,wa,"f").enableResultCrossVerification(2,!1),yield this._cvRouter.addResultFilter(e(this,wa,"f"));const t=new Ye;t.onCapturedResultReceived=()=>{},this._cvRouter.addResultReceiver(t);const s=yield this._cvRouter.capture(n,r);return e(this,wa,"f").enableResultCrossVerification(2,!0),yield this._cvRouter.addResultFilter(e(this,wa,"f")),this._cvRouter.removeResultReceiver(t),s})}dispose(){var t,n,r,s,o,a,h;i(this,pa,!0,"f"),e(Xa,da,"f",fa)&&e(Xa,da,"f",fa).isPending&&e(Xa,da,"f",fa).resolve(e(this,ma,"f")),null===(t=this._cameraEnhancer)||void 0===t||t.dispose(),null===(n=this._cameraView)||void 0===n||n.dispose(),null===(r=this._cvRouter)||void 0===r||r.dispose(),this._cameraEnhancer=null,this._cameraView=null,this._cvRouter=null,window.removeEventListener("resize",e(this,ga,"f")),null===(s=document.querySelector(".scanner-view-container"))||void 0===s||s.remove(),null===(o=document.querySelector(".result-view-container"))||void 0===o||o.remove(),null===(a=document.querySelector(".barcode-scanner-container"))||void 0===a||a.remove(),null===(h=document.querySelector(".loading-page"))||void 0===h||h.remove()}}da=Xa,ga=new WeakMap,ma=new WeakMap,pa=new WeakMap,_a=new WeakMap,va=new WeakMap,ya=new WeakMap,wa=new WeakMap,ua=new WeakSet,Ca=function(){return t(this,void 0,void 0,function*(){try{if(this.config.onInitPrepare&&this.config.onInitPrepare(),this.disposed)return;if(yield e(this,ua,"m",Ea).call(this),this.config.onInitReady&&this.config.onInitReady({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return;try{if(document.querySelector(".loading-page span").innerText="Accessing Camera...",yield this._cameraEnhancer.open(),mo(this._cameraEnhancer.getSelectedCamera())&&this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed)return}catch(t){e(this,ua,"m",ja).call(this,document.querySelector(".btn-upload-image"),!0),e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!1}),document.querySelector(".btn-camera-switch-control").style.display="none";if(document.querySelector(".no-camera-view").style.display="flex",this.disposed)return}if(this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,va,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.disposed))return}catch(t){e(this,ma,"f").status={code:l.RS_FAILED,message:t.message||t},e(Xa,da,"f",fa).reject(new Error(e(this,ma,"f").status.message)),this.dispose()}finally{e(this,ua,"m",Va).call(this,"Loading...",!1)}})},Ea=function(n=!1){return t(this,void 0,void 0,function*(){if(Ht.engineResourcePaths=this.config.engineResourcePaths,!n){const t=V(Ht.engineResourcePaths);if(this._cameraView=yield Br.createInstance(t.dbrBundle+"ui/dce.ui.xml"),this.disposed)return;if(this._cameraView._createDrawingLayer(2),this.config.scanMode===a.SM_SINGLE||this.config.scannerViewConfig.customHighlightForBarcode){this._cameraView.getDrawingLayer(2).setVisible(!1)}if(this._cameraEnhancer=yield Ds.createInstance(this._cameraView),this.disposed)return;if(yield e(this,ua,"m",ba).call(this),this.disposed)return;this.config.scannerViewConfig.customHighlightForBarcode&&i(this,ya,this._cameraEnhancer.getCameraView().createDrawingLayer(),"f")}yield ho.initLicense(this.config.license||"",{executeNow:!0}),this.disposed||(this._cvRouter=this._cvRouter||(yield We.createInstance()),this.disposed||(this.config.scanMode!==a.SM_SINGLE||n?this._cvRouter._dynamsoft=!0:this._cvRouter._dynamsoft=!1,this._cvRouter.onCaptureError=t=>{e(Xa,da,"f",fa).reject(new Error(t.message)),this.dispose()},yield e(this,ua,"m",Sa).call(this,n),this.disposed||n||(this._cvRouter.setInput(this._cameraEnhancer),e(this,ua,"m",La).call(this),yield e(this,ua,"m",Ma).call(this),this.disposed)))})},Sa=function(n=!1){return t(this,void 0,void 0,function*(){if(n||(this.config.scanMode===a.SM_SINGLE?i(this,va,this.config.utilizedTemplateNames.single,"f"):this.config.scanMode===a.SM_MULTI_UNIQUE&&i(this,va,this.config.utilizedTemplateNames.multi_unique,"f")),this.config.templateFilePath&&(yield this._cvRouter.initSettings(this.config.templateFilePath),this.disposed))return;const t=yield this._cvRouter.getSimplifiedSettings(e(this,va,"f"));if(this.disposed)return;n||this.config.scanMode!==a.SM_SINGLE||(t.outputOriginalImage=!0);let r=this.config.barcodeFormats;if(r){Array.isArray(r)||(r=[r]),t.barcodeSettings.barcodeFormatIds=BigInt(0);for(let e=0;e{document.head.appendChild(t.cloneNode(!0))}),this.config.scanMode===a.SM_SINGLE){const t=document.createElement("style");t.innerText="@keyframes result-option-flash {\n from {transform: translate(-50%, -50%) scale(1);}\n to {transform: translate(-50%, -50%) scale(0.8);}\n }";this._cameraView.getUIElement().shadowRoot.append(t)}i(this,_a,s.querySelector(".result-item"),"f"),e(this,ua,"m",Ta).call(this,s),e(this,ua,"m",Ia).call(this,s),e(this,ua,"m",xa).call(this,s),e(this,ua,"m",Oa).call(this,s),yield e(this,ua,"m",Ra).call(this,s),e(this,ua,"m",ja).call(this,s.querySelector(".btn-upload-image"),this.config.showUploadImageButton),e(this,ua,"m",Da).call(this,s),e(this,ua,"m",Aa).call(this,s)})},Ta=function(t){var i,n,r;const s=t.querySelector(".btn-clear");if(s&&(s.addEventListener("click",()=>{e(this,ma,"f").barcodeResults=[],e(this,ua,"m",Na).call(this)}),null===(r=null===(n=null===(i=this.config)||void 0===i?void 0:i.resultViewConfig)||void 0===n?void 0:n.toolbarButtonsConfig)||void 0===r?void 0:r.clear)){const e=this.config.resultViewConfig.toolbarButtonsConfig.clear;s.style.display=e.isHidden?"none":"flex",s.className=e.className?e.className:"btn-clear",s.innerText=e.label?e.label:"Clear",e.isHidden&&(t.querySelector(".toolbar-btns").style.justifyContent="center")}},Ia=function(t){var e,i,n;const r=t.querySelector(".btn-done");if(r&&(r.addEventListener("click",()=>{const t=document.querySelector(".loading-page");t&&"none"===getComputedStyle(t).display&&this.dispose()}),null===(n=null===(i=null===(e=this.config)||void 0===e?void 0:e.resultViewConfig)||void 0===i?void 0:i.toolbarButtonsConfig)||void 0===n?void 0:n.done)){const e=this.config.resultViewConfig.toolbarButtonsConfig.done;r.style.display=e.isHidden?"none":"flex",r.className=e.className?e.className:"btn-done",r.innerText=e.label?e.label:"Done",e.isHidden&&(t.querySelector(".toolbar-btns").style.justifyContent="center")}},xa=function(t){var i,n;if(null===(n=null===(i=this.config)||void 0===i?void 0:i.scannerViewConfig)||void 0===n?void 0:n.showCloseButton){const i=t.querySelector(".btn-close");i&&(i.style.display="",i.addEventListener("click",()=>{e(this,ma,"f").barcodeResults=[],e(this,ma,"f").status={code:l.RS_CANCELLED,message:"Cancelled."},this.dispose()}))}},Oa=function(i){var n;if(null===(n=this.config)||void 0===n?void 0:n.scannerViewConfig.showFlashButton){const n=i.querySelector(".btn-flash-auto"),r=i.querySelector(".btn-flash-open"),s=i.querySelector(".btn-flash-close");if(n){n.style.display="";let i=null,o=250,a=20,h=3;const l=(l=250)=>t(this,void 0,void 0,function*(){const c=this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{};if(!(null==c?void 0:c.torch))return;if(null!==i){if(!(lt(this,void 0,void 0,function*(){var t;if(e(this,pa,"f")||this._cameraEnhancer.disposed||u||void 0!==this._cameraEnhancer.isTorchOn||!this._cameraEnhancer.isOpen())return clearInterval(i),void(i=null);if(this._cameraEnhancer.isPaused())return;if(++f>10&&o<1e3)return clearInterval(i),i=null,void this._cameraEnhancer.turnAutoTorch(1e3);let l;try{l=this._cameraEnhancer.fetchImage()}catch(t){}if(!l||!l.width||!l.height)return;let c=0;if(_.IPF_GRAYSCALED===l.format){for(let t=0;t=h){null===(t=Ds._onLog)||void 0===t||t.call(Ds,`darkCount ${d}`);try{yield this._cameraEnhancer.turnOnTorch(),this._cameraEnhancer.isTorchOn=!0,n.style.display="none",r.style.display="",s.style.display="none"}catch(t){console.warn(t),u=!0}}}else d=0});i=setInterval(g,l),this._cameraEnhancer.isTorchOn=void 0,g()});this._cameraEnhancer.on("cameraOpen",()=>{!(this._cameraEnhancer.isOpen()&&!this._cameraEnhancer.cameraManager.videoSrc?this._cameraEnhancer.cameraManager.getCameraCapabilities():{}).torch&&this.config.scannerViewConfig.showFlashButton&&e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!0}),l(1e3)}),n.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOnTorch(),n.style.display="none",r.style.display="",s.style.display="none"})),r.addEventListener("click",()=>t(this,void 0,void 0,function*(){yield this._cameraEnhancer.turnOffTorch(),n.style.display="none",r.style.display="none",s.style.display=""})),s.addEventListener("click",()=>t(this,void 0,void 0,function*(){l(1e3),n.style.display="",r.style.display="none",s.style.display="none"}))}}},Ra=function(i){return t(this,void 0,void 0,function*(){let n=this.config.scannerViewConfig.cameraSwitchControl;["toggleFrontBack","listAll","hidden"].includes(n)||(this.config.scannerViewConfig.cameraSwitchControl="hidden");if("hidden"!==this.config.scannerViewConfig.cameraSwitchControl){const n=i.querySelector(".camera-control");if(n){n.style.display="";const r=yield this._cameraEnhancer.getAllCameras(),s=this.config.scannerViewConfig.cameraSwitchControl,o=t=>{const e=document.createElement("div");return e.label=t.label,e.deviceId=t.deviceId,e._checked=t._checked,e.innerText=t.label,Object.assign(e.style,{height:"40px",backgroundColor:"#2E2E2E",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:"14px",lineHeight:"40px",padding:"0 14px",cursor:"pointer"}),e},a=()=>{if(0===r.length)return null;if("listAll"===s){const n=i.querySelector(".camera-list");for(let t of r){const e=o(t);n.append(e)}window.addEventListener("click",()=>{const t=document.querySelector(".camera-list");t&&(t.style.display="none")});const s=t=>{for(let e of a)e.label===t.label&&e.deviceId===t.deviceId?e.style.color="#FE8E14":e.style.color="#FFFFFF"};n.addEventListener("click",i=>t(this,void 0,void 0,function*(){const t=i.target;e(this,ua,"m",Va).call(this,"Accessing Camera...",!0),this._cvRouter.stopCapturing(),yield this._cameraEnhancer.selectCamera({deviceId:t.deviceId,label:t.label,_checked:t._checked});const n=this._cameraEnhancer.getSelectedCamera(),r=this._cameraEnhancer.getCapabilities();mo(n)&&this.config.scannerViewConfig.mirrorFrontCamera?this._cameraEnhancer.toggleMirroring(!0):this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&(r.torch?e(this,ua,"m",Ua).call(this,{auto:!0,open:!1,close:!1,notSupport:!1}):e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),s(n),this.config.onCameraOpen&&this.config.onCameraOpen({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter}),this.config.autoStartCapturing&&(yield this._cvRouter.startCapturing(e(this,va,"f")),this.config.onCaptureStart&&this.config.onCaptureStart({cameraView:this._cameraView,cameraEnhancer:this._cameraEnhancer,cvRouter:this._cvRouter})),e(this,ua,"m",Va).call(this,"Loading...",!1)}));const a=i.querySelectorAll(".camera-list div");return()=>t(this,void 0,void 0,function*(){const t=this._cameraEnhancer.getSelectedCamera();s(t);const e=document.querySelector(".camera-list");"none"===getComputedStyle(e).display?e.style.display="":e.style.display="none"})}return"toggleFrontBack"===s?()=>t(this,void 0,void 0,function*(){e(this,ua,"m",Va).call(this,"Accessing Camera...",!0);const t=mo(this._cameraEnhancer.getSelectedCamera());yield this._cameraEnhancer.updateVideoSettings({video:{facingMode:{ideal:t?"environment":"user"}}}),t?(this._cameraEnhancer.toggleMirroring(!1),this.config.scannerViewConfig.showFlashButton&&e(this,ua,"m",Ua).call(this,{auto:!0,open:!1,close:!1,notSupport:!1})):(this.config.scannerViewConfig.mirrorFrontCamera&&this._cameraEnhancer.toggleMirroring(!0),this.config.scannerViewConfig.showFlashButton&&e(this,ua,"m",Ua).call(this,{auto:!1,open:!1,close:!1,notSupport:!0})),e(this,ua,"m",Va).call(this,"Loading...",!1)}):void 0},h=a();n.addEventListener("click",e=>t(this,void 0,void 0,function*(){e.stopPropagation(),h&&(yield h())}))}}})},Aa=function(t){const n=this._cameraView.getUIElement();n.shadowRoot.querySelector(".dce-sel-camera").remove(),n.shadowRoot.querySelector(".dce-sel-resolution").remove(),this._cameraView.setVideoFit("cover");const r=t.querySelector(".barcode-scanner-container");r.style.display=uo()?"flex":"",this.config.scanMode===a.SM_MULTI_UNIQUE&&!1!==this.config.showResultView?this.config.showResultView=!0:this.config.scanMode===a.SM_SINGLE&&(this.config.showResultView=!1);const s=this.config.showResultView;let o;if(this.config.container?(r.style.position="relative",o=this.config.container):o=document.body,"string"==typeof o&&(o=document.querySelector(o),null===o))throw new Error("Failed to get the container");let h=this.config.scannerViewConfig.container;if("string"==typeof h&&(h=document.querySelector(h),null===h))throw new Error("Failed to get the container of the scanner view.");let l=this.config.resultViewConfig.container;if("string"==typeof l&&(l=document.querySelector(l),null===l))throw new Error("Failed to get the container of the result view.");const c=t.querySelector(".scanner-view-container"),u=t.querySelector(".result-view-container"),d=t.querySelector(".loading-page");c.append(d),h&&(c.append(n),h.append(c)),l&&l.append(u),h||l?h&&!l?(this.config.container||(u.style.position="absolute"),l=u,o.append(u)):!h&&l&&(this.config.container||(c.style.position="absolute"),h=c,c.append(n),o.append(c)):(h=c,l=u,s&&(Object.assign(c.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"}),Object.assign(u.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"})),c.append(n),o.append(r)),document.querySelector(".result-view-container").style.display=s?"":"none",this.config.showPoweredByDynamsoft||(this._cameraView.setPowerByMessageVisible(!1),document.querySelector(".no-result-svg").style.display="none"),i(this,ga,()=>{Object.assign(r.style,{display:uo()?"flex":""}),!s||this.config.scannerViewConfig.container||this.config.resultViewConfig.container||(Object.assign(h.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"}),Object.assign(l.style,{width:uo()?"50%":"100%",height:uo()?"100%":"50%"}))},"f"),window.addEventListener("resize",e(this,ga,"f"))},Da=function(i){i.querySelector(".resume").addEventListener("click",()=>t(this,void 0,void 0,function*(){document.querySelector(".features-group").style.display="flex",document.querySelector(".btn-close").style.display="block",document.querySelector(".resume").style.display="none",this._cameraView.getUIElement().shadowRoot.querySelector(".single-mode-mask").remove(),this._cameraView.getUIElement().shadowRoot.querySelectorAll(".single-barcode-result-option").forEach(t=>t.remove()),yield this._cameraEnhancer.resume(),yield new Promise(t=>{setTimeout(t,100)}),this._cvRouter.startCapturing(e(this,va,"f"))}))},La=function(){const i=new Ye;i.onCapturedResultReceived=i=>t(this,void 0,void 0,function*(){if(e(this,ya,"f")&&e(this,ya,"f").clearDrawingItems(),i.decodedBarcodesResult){if(this.config.scannerViewConfig.customHighlightForBarcode){let t=[];for(let e of i.decodedBarcodesResult.barcodeResultItems)t.push(this.config.scannerViewConfig.customHighlightForBarcode(e));e(this,ya,"f").addDrawingItems(t)}this.config.scanMode===a.SM_SINGLE?e(this,ua,"m",Fa).call(this,i):e(this,ua,"m",Pa).call(this,i)}}),this._cvRouter.addResultReceiver(i)},Ma=function(){return t(this,void 0,void 0,function*(){e(this,wa,"f")||i(this,wa,new oa,"f"),e(this,wa,"f").enableResultCrossVerification(2,!0),e(this,wa,"f").enableResultDeduplication(2,!0),e(this,wa,"f").setDuplicateForgetTime(2,this.config.duplicateForgetTime),yield this._cvRouter.addResultFilter(e(this,wa,"f")),e(this,wa,"f").isResultCrossVerificationEnabled=()=>!1,e(this,wa,"f").isResultDeduplicationEnabled=()=>!1})},Fa=function(t){const i=this._cameraView.getUIElement().shadowRoot;let n=new Promise(n=>{if(t.decodedBarcodesResult.barcodeResultItems.length>1){e(this,ua,"m",ka).call(this);let r=[];for(let e of t.decodedBarcodesResult.barcodeResultItems){let t=0,i=0;for(let n=0;n<4;++n){let r=e.location.points[n];t+=r.x,i+=r.y}let s=this._cameraEnhancer.convertToClientCoordinates({x:t/4,y:i/4}),o=document.createElement("div");o.className="single-barcode-result-option",Object.assign(o.style,{position:"fixed",width:"25px",height:"25px",border:"#fff solid 4px",transform:"translate(-50%, -50%)",animation:"1s infinite alternate result-option-flash","box-sizing":"border-box","border-radius":"16px",background:"#080",cursor:"pointer"}),o.style.left=s.x+"px",o.style.top=s.y+"px",o.addEventListener("click",()=>{n(e)}),r.push(o)}i.append(...r)}else n(t.decodedBarcodesResult.barcodeResultItems[0])});n.then(i=>{const n=t.items.filter(t=>t.type===ft.CRIT_ORIGINAL_IMAGE)[0].imageData,r={status:{code:l.RS_SUCCESS,message:"Success."},originalImageResult:n,barcodeImage:(()=>{const t=W(n),e=i.location.points,r=Math.min(...e.map(t=>t.x)),s=Math.min(...e.map(t=>t.y)),o=Math.max(...e.map(t=>t.x)),a=Math.max(...e.map(t=>t.y)),h=o-r,l=a-s,c=document.createElement("canvas");c.width=h,c.height=l;const u=c.getContext("2d");u.beginPath(),u.moveTo(e[0].x-r,e[0].y-s);for(let t=1;t`${t.formatString}_${t.text}`==`${i.formatString}_${i.text}`);-1===t?(i.count=1,e(this,ma,"f").barcodeResults.unshift(i),e(this,ua,"m",Na).call(this,i)):(e(this,ma,"f").barcodeResults[t].count++,e(this,ua,"m",Ba).call(this,t)),this.config.onUniqueBarcodeScanned&&this.config.onUniqueBarcodeScanned(i)}},ka=function(){const t=this._cameraView.getUIElement().shadowRoot;if(t.querySelector(".single-mode-mask"))return;const e=document.createElement("div");e.className="single-mode-mask",Object.assign(e.style,{width:"100%",height:"100%",position:"absolute",top:"0",left:"0",right:"0",bottom:"0",opacity:"0.5","background-color":"#4C4C4C"}),t.append(e),document.querySelector(".features-group").style.display="none",document.querySelector(".btn-close").style.display="none",document.querySelector(".resume").style.display="block",this._cameraEnhancer.pause(),this._cvRouter.stopCapturing()},Na=function(t){if(!this.config.showResultView)return;const i=document.querySelector(".no-result-svg");if(!(this.config.showResultView&&this.config.scanMode!==a.SM_SINGLE))return;const n=document.querySelector(".main-list");if(!t)return n.textContent="",void(this.config.showPoweredByDynamsoft&&(i.style.display=""));i.style.display="none";const r=(t=>{const i=e(this,_a,"f").cloneNode(!0);i.querySelector(".format-string").innerText=t.formatString;i.querySelector(".text-string").innerText=t.text.replace(/\n|\r/g,""),i.id=`${t.formatString}_${t.text}`;return i.querySelector(".delete-icon").addEventListener("click",()=>{const i=[...document.querySelectorAll(".main-list .result-item")],n=i.findIndex(e=>e.id===`${t.formatString}_${t.text}`);e(this,ma,"f").barcodeResults.splice(n,1),i[n].remove(),0===e(this,ma,"f").barcodeResults.length&&this.config.showPoweredByDynamsoft&&(document.querySelector(".no-result-svg").style.display="")}),i})(t);n.insertBefore(r,document.querySelector(".result-item"))},Ba=function(t){if(!this.config.showResultView)return;const e=document.querySelectorAll(".main-list .result-item"),i=e[t].querySelector(".result-count");let n=parseInt(i.textContent.replace("x",""));e[t].querySelector(".result-count").textContent="x"+ ++n},ja=function(i,n){n&&(i.style.display="",i.onchange=i=>t(this,void 0,void 0,function*(){const t=i.target.files,n={status:{code:l.RS_SUCCESS,message:"Success."},barcodeResults:[]};let r=0;e(this,ua,"m",Va).call(this,`Capturing... [${r}/${t.length}]`,!0);let s=!1;for(let e=0;e`${e.formatString}_${e.text}`==`${t.formatString}_${t.text}`);-1===i?(t.count=1,e(this,ma,"f").barcodeResults.unshift(t),e(this,ua,"m",Na).call(this,t)):(e(this,ma,"f").barcodeResults[i].count++,e(this,ua,"m",Ba).call(this,i))}else if(s.decodedBarcodesResult.barcodeResultItems)for(let t of s.decodedBarcodesResult.barcodeResultItems){const e=n.barcodeResults.find(e=>`${e.text}_${e.formatString}`==`${t.text}_${t.formatString}`);e?e.count++:(t.count=1,n.barcodeResults.push(t))}e(this,ua,"m",Va).call(this,`Capturing... [${++r}/${t.length}]`,!0)}catch(t){n.status={code:l.RS_FAILED,message:t.message||t},e(Xa,da,"f",fa).reject(new Error(n.status.message)),this.dispose()}e(this,ua,"m",Va).call(this,"Loading...",!1),this.config.scanMode===a.SM_SINGLE&&(e(Xa,da,"f",fa).resolve(n),this.dispose()),i.target.value=""}))},Ua=function(t){document.querySelector(".btn-flash-not-support").style.display=t.notSupport?"":"none",document.querySelector(".btn-flash-auto").style.display=t.auto?"":"none",document.querySelector(".btn-flash-open").style.display=t.open?"":"none",document.querySelector(".btn-flash-close").style.display=t.close?"":"none"},Va=function(t,e){const i=document.querySelector(".loading-page"),n=document.querySelector(".loading-page span");n&&(n.innerText=t),i&&(i.style.display=e?"flex":"none")},Ga=function(t){let e=Ft();Pt[e]=()=>{},Lt.postMessage({type:"cvr_cc",id:e,instanceID:this._cvRouter._instanceID,body:{text:t.text,strFormat:t.format.toString(),isDPM:t.isDPM}})},fa={value:null};const za="undefined"==typeof self,qa="function"==typeof importScripts,Ka=(()=>{if(!qa){if(!za&&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"./"}})(),Za=t=>{if(null==t&&(t="./"),za||qa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};Ht.engineResourcePaths.dbr={version:"11.2.20-dev-20251029130556",path:Ka,isInternal:!0},Gt.dbr={js:!1,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE,xt.MN_DYNAMSOFT_IMAGE_PROCESSING]},Vt.dbr={};const Ja="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,Ja)<0&&(Ht.engineResourcePaths.std={version:Ja,path:Za(Ka+`../../dynamsoft-capture-vision-std@${Ja}/dist/`),isInternal:!0});const $a="3.0.10";(!Ht.engineResourcePaths.dip||"string"!=typeof Ht.engineResourcePaths.dip&&U(Ht.engineResourcePaths.dip.version,$a)<0)&&(Ht.engineResourcePaths.dip={version:$a,path:Za(Ka+`../../dynamsoft-image-processing@${$a}/dist/`),isInternal:!0});let Qa=class{static getVersion(){const t=Ut.dbr&&Ut.dbr.wasm;return`11.2.20-dev-20251029130556(Worker: ${Ut.dbr&&Ut.dbr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}};const th={BF_NULL:BigInt(0),BF_ALL:BigInt("0xFFFFFFFEFFFFFFFF"),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552),BF_TELEPEN:BigInt(137438953472),BF_TELEPEN_NUMERIC:BigInt(274877906944)};var eh,ih,nh,rh,sh,oh;function ah(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:hh(e,t,"map"),t.getFieldRawValue=t=>hh(e,t,"raw"),t.getFieldMappingStatus=t=>lh(e,t),t.getFieldValidationStatus=t=>ch(e,t),delete t.fullCodeString}function hh(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=hh(r,e,i);if(void 0!==t)return t}}}function lh(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(sh[i.MappingStatus]):sh.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=lh(n,e);if(void 0!==t)return t}}}function ch(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(oh[i.ValidationStatus]):oh.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=ch(n,e);if(void 0!==t)return t}}}function uh(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!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"}(eh||(eh={})),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"}(ih||(ih={})),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_NEURAL_NETWORK=512]="LM_NEURAL_NETWORK",t[t.LM_REV=-2147483648]="LM_REV",t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_END=-1]="LM_END"}(nh||(nh={})),function(t){t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",t[t.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",t[t.DM_REV=-2147483648]="DM_REV",t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_END=-1]="DM_END"}(rh||(rh={})),function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(sh||(sh={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(oh||(oh={}));const dh=t=>t&&"object"==typeof t&&"function"==typeof t.then,fh=(async()=>{})().constructor;class gh extends fh{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,dh(t)?e=t:"function"==typeof t&&(e=new fh(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super((t,n)=>{e=t,i=n}),this._s="pending",this.resolve=t=>{this.isPending&&(dh(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class mh{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!Vt.license)throw Error("Module `license` is not existed.");await Vt.license.dynamsoft(),await Ht.loadWasm();const t=new mh,e=new gh;let i=Ft();return Pt[i]=async i=>{if(i.success)t._instanceID=i.instanceID,e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},Lt.postMessage({type:"dcp_createInstance",id:i}),e}async dispose(){uh(this);let t=Ft();this.bDestroyed=!0,Pt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},Lt.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){if(uh(this),t&&["string","object"].includes(typeof t))return"string"==typeof t?t.trimStart().startsWith("{")||(t=await B(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise((e,i)=>{let n=Ft();Pt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},Lt.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})});console.error("Invalid settings.")}async resetSettings(){return uh(this),await new Promise((t,e)=>{let i=Ft();Pt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},Lt.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})})}async parse(t,e=""){if(uh(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise((i,n)=>{let r=Ft();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(ah(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},Lt.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})})}}const ph="undefined"==typeof self,_h="function"==typeof importScripts,vh=(()=>{if(!_h){if(!ph&&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"./"}})();Ht.engineResourcePaths.dcp={version:"3.2.20-dev-20251029130614",path:vh,isInternal:!0},Gt.dcp={js:!0,wasm:!0,deps:[xt.MN_DYNAMSOFT_LICENSE]},Vt.dcp={handleParsedResultItem:ah};const yh="2.0.0";"string"!=typeof Ht.engineResourcePaths.std&&U(Ht.engineResourcePaths.std.version,yh)<0&&(Ht.engineResourcePaths.std={version:yh,path:(t=>{if(null==t&&(t="./"),ph||_h);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(vh+`../../dynamsoft-capture-vision-std@${yh}/dist/`),isInternal:!0}),Pt[-4]=async t=>{wh.onSpecLoadProgressChanged&&wh.onSpecLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};class wh{static getVersion(){const t=Ut.dcp&&Ut.dcp.wasm;return`3.2.20-dev-20251029130614(Worker: ${Ut.dcp&&Ut.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await Ht.loadWasm(),await new Promise((i,n)=>{let r=Ft();Pt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],o=V(Ht.engineResourcePaths);Lt.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||`${"DBR"===Ht._bundleEnv?o.dbrBundle:o.dcvData}parser-resources/`,specificationNames:s}})})}}Ht._bundleEnv="DBR",We._defaultTemplate="ReadSingleBarcode",Ht.engineResourcePaths.rootDirectory=o(s+"../../"),Ht.engineResourcePaths.dbrBundle={version:"11.2.2000",path:s,isInternal:!0};export{Qa as BarcodeReaderModule,Xa as BarcodeScanner,Ds as CameraEnhancer,ei as CameraEnhancerModule,Vr as CameraManager,Br as CameraView,We as CaptureVisionRouter,fe as CaptureVisionRouterModule,Ye as CapturedResultReceiver,mh as CodeParser,wh as CodeParserModule,Ht as CoreModule,Ai as DrawingItem,Lr as DrawingStyleManager,th as EnumBarcodeFormat,m as EnumBufferOverflowProtectionMode,ft as EnumCapturedResultItemType,p as EnumColourChannelUsageType,gt as EnumCornerType,Ct as EnumCrossVerificationStatus,rh as EnumDeblurMode,di as EnumDrawingItemMediaType,fi as EnumDrawingItemState,gi as EnumEnhancedFeatures,mt as EnumErrorCode,eh as EnumExtendedBarcodeResultType,ca as EnumFilterType,pt as EnumGrayscaleEnhancementMode,_t as EnumGrayscaleTransformationMode,It as EnumImageCaptureDistanceMode,Tt as EnumImageFileFormat,_ as EnumImagePixelFormat,ge as EnumImageSourceState,vt as EnumImageTagType,Et as EnumIntermediateResultUnitType,nh as EnumLocalizationMode,sh as EnumMappingStatus,xt as EnumModuleName,h as EnumOptimizationMode,yt as EnumPDFReadingMode,Xe as EnumPresetTemplate,ih as EnumQRCodeErrorCorrectionLevel,wt as EnumRasterDataSource,St as EnumRegionObjectElementType,l as EnumResultStatus,a as EnumScanMode,bt as EnumSectionType,Ot as EnumTransformMatrixType,oh as EnumValidationStatus,Ts as Feedback,Yi as GroupDrawingItem,jr as ImageDataGetter,Ya as ImageDrawer,Ni as ImageDrawingItem,Vs as ImageEditorView,Wa as ImageIO,Ha as ImageProcessor,ht as ImageSourceAdapter,He as IntermediateResultReceiver,ho as LicenseManager,co as LicenseModule,Gi as LineDrawingItem,oa as MultiFrameResultCrossFilter,Wi as QuadDrawingItem,Di as RectDrawingItem,ji as TextDrawingItem,bo as UtilityModule,X as _getNorImageData,G as _saveToFile,H as _toBlob,W as _toCanvas,Y as _toImage,Bt as bDebug,j as checkIsLink,U as compareVersion,Dt as doOrWaitAsyncDependency,Ft as getNextTaskID,V as handleEngineResourcePaths,Ut as innerVersions,I as isArc,x as isContour,A as isDSImageData,D as isDSRect,L as isImageTag,M as isLineSegment,T as isObject,R as isOriginalDsImageData,F as isPoint,P as isPolygon,k as isQuad,N as isRect,z as isSimdSupported,Rt as mapAsyncDependency,Vt as mapPackageRegister,Pt as mapTaskCallBack,kt as onLog,q as productNameMap,B as requestResource,jt as setBDebug,Nt as setOnLog,At as waitAsyncDependency,Lt as worker,Gt as workerAutoResources}; diff --git a/dist/dbr.bundle.worker.js b/dist/dbr.bundle.worker.js index 6c0ea21..48b4b1d 100644 --- a/dist/dbr.bundle.worker.js +++ b/dist/dbr.bundle.worker.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2025, Dynamsoft Corporation * @author Dynamsoft -* @version 11.0.6000 +* @version 11.2.2000 * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on dbr JS: https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/ */ -!function(){"use strict";function e(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{_(n.next(e))}catch(e){s(e)}}function a(e){try{_(n.throw(e))}catch(e){s(e)}}function _(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}_((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const t=e=>e&&"object"==typeof e&&"function"==typeof e.then,r=(async()=>{})().constructor;class n extends r{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let n;this._task=e,t(e)?n=e:"function"==typeof e&&(n=new r(e)),n&&(async()=>{try{const t=await n;e===this._task&&this.resolve(t)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let r,n;super((e,t)=>{r=e,n=t}),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",r(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}}const i=e=>e&&"object"==typeof e&&"function"==typeof e.then,s=(async()=>{})().constructor;let o=class extends s{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,i(e)?t=e:"function"==typeof e&&(t=new s(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,r;super((e,n)=>{t=e,r=n}),this._s="pending",this.resolve=e=>{this.isPending&&(i(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",r(e))},this.task=e}};var a,_,c;"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.BOPM_BLOCK=0]="BOPM_BLOCK",e[e.BOPM_UPDATE=1]="BOPM_UPDATE"}(a||(a={})),function(e){e[e.CCUT_AUTO=0]="CCUT_AUTO",e[e.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",e[e.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",e[e.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",e[e.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",e[e.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(_||(_={})),function(e){e[e.IPF_BINARY=0]="IPF_BINARY",e[e.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",e[e.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",e[e.IPF_NV21=3]="IPF_NV21",e[e.IPF_RGB_565=4]="IPF_RGB_565",e[e.IPF_RGB_555=5]="IPF_RGB_555",e[e.IPF_RGB_888=6]="IPF_RGB_888",e[e.IPF_ARGB_8888=7]="IPF_ARGB_8888",e[e.IPF_RGB_161616=8]="IPF_RGB_161616",e[e.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",e[e.IPF_ABGR_8888=10]="IPF_ABGR_8888",e[e.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",e[e.IPF_BGR_888=12]="IPF_BGR_888",e[e.IPF_BINARY_8=13]="IPF_BINARY_8",e[e.IPF_NV12=14]="IPF_NV12",e[e.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(c||(c={}));const d="undefined"==typeof self,l="function"==typeof importScripts,E=(()=>{if(!l){if(!d&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),u=e=>{if(null==e&&(e="./"),d||l);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e},f=e=>"number"==typeof e&&!Number.isNaN(e),I=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),m=e=>!(!(e=>!(!I(e)||!f(e.width)||e.width<=0||!f(e.height)||e.height<=0||!f(e.stride)||e.stride<=0||!("format"in e)||"tag"in e&&!T(e.tag)))(e)||!f(e.bytes.length)&&!f(e.bytes.ptr)),T=e=>null===e||!!I(e)&&!!f(e.imageId)&&"type"in e,C=async(e,t)=>await new Promise((r,n)=>{let i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType=t,i.send(),i.onloadend=async()=>{i.status<200||i.status>=300?n(new Error(e+" "+i.status)):r(i.response)},i.onerror=()=>{n(new Error("Network Error: "+i.statusText))}}),g=(e,t)=>{let r=e.split("."),n=t.split(".");for(let e=0;e{let e=!1;if(S)try{(await N.getUserMedia({video:!0})).getTracks().forEach(e=>{e.stop()}),e=!0}catch(e){}return e};var b,L,M,w,U,P,B,F,G;"Chrome"===v.browser&&v.version>66||"Safari"===v.browser&&v.version>13||"OPR"===v.browser&&v.version>43||"Edge"===v.browser&&v.version,function(e){e[e.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",e[e.CRIT_BARCODE=2]="CRIT_BARCODE",e[e.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",e[e.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",e[e.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",e[e.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",e[e.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(b||(b={})),function(e){e[e.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",e[e.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",e[e.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",e[e.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(L||(L={})),function(e){e[e.EC_OK=0]="EC_OK",e[e.EC_UNKNOWN=-1e4]="EC_UNKNOWN",e[e.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",e[e.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",e[e.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",e[e.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",e[e.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",e[e.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",e[e.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",e[e.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",e[e.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",e[e.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",e[e.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",e[e.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",e[e.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",e[e.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",e[e.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",e[e.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",e[e.EC_TIMEOUT=-10026]="EC_TIMEOUT",e[e.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",e[e.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",e[e.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",e[e.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",e[e.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",e[e.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",e[e.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",e[e.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",e[e.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",e[e.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",e[e.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",e[e.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",e[e.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",e[e.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",e[e.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",e[e.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",e[e.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",e[e.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",e[e.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",e[e.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",e[e.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",e[e.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",e[e.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",e[e.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",e[e.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",e[e.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",e[e.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",e[e.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",e[e.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",e[e.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",e[e.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",e[e.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",e[e.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",e[e.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",e[e.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",e[e.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",e[e.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",e[e.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",e[e.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",e[e.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",e[e.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",e[e.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",e[e.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",e[e.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",e[e.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",e[e.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",e[e.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",e[e.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",e[e.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",e[e.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",e[e.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",e[e.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",e[e.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",e[e.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",e[e.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",e[e.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",e[e.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",e[e.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",e[e.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",e[e.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",e[e.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",e[e.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",e[e.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",e[e.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(M||(M={})),function(e){e[e.GEM_SKIP=0]="GEM_SKIP",e[e.GEM_AUTO=1]="GEM_AUTO",e[e.GEM_GENERAL=2]="GEM_GENERAL",e[e.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",e[e.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",e[e.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",e[e.GEM_REV=-2147483648]="GEM_REV",e[e.GEM_END=-1]="GEM_END"}(w||(w={})),function(e){e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_AUTO=4]="GTM_AUTO",e[e.GTM_REV=-2147483648]="GTM_REV",e[e.GTM_END=-1]="GTM_END"}(U||(U={})),function(e){e[e.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",e[e.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(P||(P={})),function(e){e[e.PDFRM_VECTOR=1]="PDFRM_VECTOR",e[e.PDFRM_RASTER=2]="PDFRM_RASTER",e[e.PDFRM_REV=-2147483648]="PDFRM_REV"}(B||(B={})),function(e){e[e.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",e[e.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(F||(F={})),function(e){e[e.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",e[e.CVS_PASSED=1]="CVS_PASSED",e[e.CVS_FAILED=2]="CVS_FAILED"}(G||(G={}));const k={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var W,V,x,H,Y,j;!function(e){e[e.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",e[e.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",e[e.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",e[e.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",e[e.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",e[e.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",e[e.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",e[e.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",e[e.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",e[e.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(W||(W={})),function(e){e[e.ST_NULL=0]="ST_NULL",e[e.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",e[e.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",e[e.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",e[e.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",e[e.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",e[e.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",e[e.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",e[e.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(V||(V={})),function(e){e[e.IFF_JPEG=0]="IFF_JPEG",e[e.IFF_PNG=1]="IFF_PNG",e[e.IFF_BMP=2]="IFF_BMP",e[e.IFF_PDF=3]="IFF_PDF"}(x||(x={})),function(e){e[e.ICDM_NEAR=0]="ICDM_NEAR",e[e.ICDM_FAR=1]="ICDM_FAR"}(H||(H={})),function(e){e.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",e.MN_DYNAMSOFT_CORE="core",e.MN_DYNAMSOFT_LICENSE="license",e.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",e.MN_DYNAMSOFT_UTILITY="utility",e.MN_DYNAMSOFT_BARCODE_READER="dbr",e.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",e.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",e.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",e.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",e.MN_DYNAMSOFT_CODE_PARSER="dcp",e.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",e.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(Y||(Y={})),function(e){e[e.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",e[e.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",e[e.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",e[e.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(j||(j={}));const J={},$=async e=>{let t="string"==typeof e?[e]:e,r=[];for(let e of t)r.push(J[e]=J[e]||new o);await Promise.all(r)};let X,K=0;const Z=()=>K++,Q={};let z;let q=!1;const ee={},te={dip:{wasm:!0}},re={std:{version:"2.0.0",path:u(E+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.0.60-dev-20250812165815",path:E,isInternal:!0}};class ne{static get engineResourcePaths(){return re}static set engineResourcePaths(e){Object.assign(re,e)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return z}static set _onLog(e){(e=>{z=e,X&&X.postMessage({type:"setBLog",body:{value:!!e}})})(e)}static get _bDebug(){return q}static set _bDebug(e){(e=>{q=e,X&&X.postMessage({type:"setBDebug",body:{value:!!e}})})(e)}static get _workerName(){return`${ne._bundleEnv.toLowerCase()}.bundle.worker.js`}static isModuleLoaded(e){return e=(e=e||"core").toLowerCase(),!!J[e]&&J[e].isFulfilled}static async loadWasm(){return await(async()=>{let e,t;e instanceof Array||(e=e?[e]:[]);let r=J.core;t=!r||r.isEmpty,t||await $("core");let n=new Map;const i=e=>{if(e=e.toLowerCase(),Y.MN_DYNAMSOFT_CAPTURE_VISION_STD==e||Y.MN_DYNAMSOFT_CORE==e)return;let t=te[e].deps;if(null==t?void 0:t.length)for(let e of t)i(e);let r=J[e];n.has(e)||n.set(e,!r||r.isEmpty)};for(let t of e)i(t);let s=[];t&&s.push("core"),s.push(...n.keys());const a=[...n.entries()].filter(e=>!e[1]).map(e=>e[0]);await(async(e,t)=>{let r,n="string"==typeof e?[e]:e,i=[];for(let e of n){let n;i.push(n=J[e]=J[e]||new o(r=r||t())),n.isEmpty&&(n.task=r=r||t())}await Promise.all(i)})(s,async()=>{const e=[...n.entries()].filter(e=>e[1]).map(e=>e[0]);await $(a);const r=(e=>{const t={};for(let r in e){if("rootDirectory"===r)continue;let n=r,i=e[n],s=i&&"object"==typeof i&&i.path?i.path:i,o=e.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof i&&i.isInternal)o&&(s=e[n].version?`${o}${p[n]}@${e[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${p[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const r=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(r,o||"")),"object"==typeof s&&"dwt"===n){const i=e[n].resourcesPath,s=e[n].serviceInstallerLocation;t[n]={resourcesPath:i.replace(r,o||""),serviceInstallerLocation:s.replace(r,o||"")};continue}}t[n]=u(s)}return t})(re),i={};for(let t of e)i[t]=te[t];const s={engineResourcePaths:r,autoResources:i,names:e,_bundleEnv:ne._bundleEnv,_useSimd:ne._useSimd,_useMLBackend:ne._useMLBackend};let _=new o;if(t){s.needLoadCore=!0;let e=r[`${ne._bundleEnv.toLowerCase()}Bundle`]+ne._workerName;e.startsWith(location.origin)||(e=await fetch(e).then(e=>e.blob()).then(e=>URL.createObjectURL(e))),X=new Worker(e),X.onerror=e=>{let t=new Error(e.message);_.reject(t)},X.addEventListener("message",e=>{let t=e.data?e.data:e,r=t.type,n=t.id,i=t.body;switch(r){case"log":z&&z(t.message);break;case"task":try{Q[n](i),delete Q[n]}catch(e){throw delete Q[n],e}break;case"event":try{Q[n](i)}catch(e){throw e}break;default:console.log(e)}}),s.bLog=!!z,s.bd=q,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await $("core");let c=K++;Q[c]=e=>{if(e.success)Object.assign(ee,e.versions),"{}"!==JSON.stringify(e.versions)&&(ne._versions=e.versions),_.resolve(void 0);else{const t=Error(e.message);e.stack&&(t.stack=e.stack),_.reject(t)}},X.postMessage({type:"loadWasm",id:c,body:s}),await _})})()}static async detectEnvironment(){return await(async()=>({wasm:A,worker:D,getUserMedia:S,camera:await O(),browser:v.browser,version:v.version,OS:v.OS}))()}static async getModuleVersion(){return await new Promise((e,t)=>{let r=Z();Q[r]=async r=>{if(r.success)return e(r.versions);{let e=new Error(r.message);return e.stack=r.stack+"\n"+e.stack,t(e)}},X.postMessage({type:"getModuleVersion",id:r})})}static getVersion(){return`4.0.60-dev-20250812165815(Worker: ${ee.core&&ee.core.worker||"Not Loaded"}, Wasm: ${ee.core&&ee.core.wasm||"Not Loaded"})`}static enableLogging(){ne._onLog=console.log}static disableLogging(){ne._onLog=null}static async cfd(e){return await new Promise((t,r)=>{let n=Z();Q[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},X.postMessage({type:"cfd",id:n,body:{count:e}})})}}ne._bSupportDce4Module=-1,ne._bSupportIRTModule=-1,ne._versions=null,ne._bundleEnv="DCV",ne._useMLBackend=!1,ne._useSimd=!0,ne.browserInfo=v;const ie="undefined"==typeof self,se=ie?{}:self;let oe,ae,_e,ce,de;"undefined"!=typeof navigator&&(oe=navigator,ae=oe.userAgent,_e=oe.platform,ce=oe.mediaDevices),function(){if(!ie){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:oe.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:_e,search:"Win"},Mac:{str:_e},Linux:{str:_e}};let r="unknownBrowser",n=0,i="unknownOS";for(let t in e){const i=e[t]||{};let s=i.str||ae,o=i.search||t,a=i.verStr||ae,_=i.verSearch||t;if(_ instanceof Array||(_=[_]),-1!=s.indexOf(o)){r=t;for(let e of _){let t=a.indexOf(e);if(-1!=t){n=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let n=r.str||ae,s=r.search||e;if(-1!=n.indexOf(s)){i=e;break}}"Linux"==i&&-1!=ae.indexOf("Windows NT")&&(i="HarmonyOS"),de={browser:r,version:n,OS:i}}ie&&(de={browser:"ssr",version:0,OS:"ssr"})}(),ce&&ce.getUserMedia;const le="Chrome"===de.browser&&de.version>66||"Safari"===de.browser&&de.version>13||"OPR"===de.browser&&de.version>43||"Edge"===de.browser&&de.version>15;var Ee=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function ue(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(i){if("TypeError"!==i.name)throw i;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}}).catch(function(){return!1})}(e).then(function(e){return ge=e,ge})}function ve(e){var t=pe[e.name],r={};r.promise=new Promise(function(e,t){r.resolve=e,r.reject=t}),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then(function(){return r.promise}):t.dbReady=r.promise}function Ae(e){var t=pe[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function De(e,t){var r=pe[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function Se(e,t){return new Promise(function(r,n){if(pe[e.name]=pe[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);ve(e),e.db.close()}var i=[e.name];t&&i.push(e.version);var s=Ee.open.apply(Ee,i);t&&(s.onupgradeneeded=function(t){var r=s.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(Ce)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),s.onerror=function(e){e.preventDefault(),n(s.error)},s.onsuccess=function(){var t=s.result;t.onversionchange=function(e){e.target.close()},r(t),Ae(e)}})}function Oe(e){return Se(e,!1)}function be(e){return Se(e,!0)}function Le(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),i||r){if(r){var s=e.db.version+1;s>e.version&&(e.version=s)}return!0}return!1}function Me(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),i=0;i0&&(!e.db||"InvalidStateError"===i.name||"NotFoundError"===i.name))return Promise.resolve().then(()=>{if(!e.db||"NotFoundError"===i.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),be(e)}).then(()=>function(e){ve(e);for(var t=pe[e.name],r=t.forages,n=0;n(e.db=t,Le(e)?be(e):t)).then(n=>{e.db=t.db=n;for(var i=0;i{throw De(e,t),t})}(e).then(function(){Ue(e,t,r,n-1)})).catch(r);r(i)}}var Pe={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var i=pe[r.name];i||(i={forages:[],db:null,dbReady:null,deferredOperations:[]},pe[r.name]=i),i.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=we);var s=[];function o(){return Promise.resolve()}for(var a=0;a{const r=pe[e.name],n=r.forages;r.db=t;for(var i=0;i{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;ve(e);const n=pe[e.name],i=n.forages;t.close();for(let e=0;e{const i=Ee.open(e.name,r);i.onerror=e=>{i.result.close(),n(e)},i.onupgradeneeded=()=>{i.result.deleteObjectStore(e.storeName)},i.onsuccess=()=>{const e=i.result;e.close(),t(e)}});return s.then(e=>{n.db=e;for(let t=0;t{throw(De(e,t)||Promise.resolve()).catch(()=>{}),t})}):t.then(t=>{ve(e);const r=pe[e.name],n=r.forages;t.close();for(var i=0;i{var n=Ee.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}});return s.then(e=>{r.db=e;for(var t=0;t{throw(De(e,t)||Promise.resolve()).catch(()=>{}),t})})}else r=Promise.reject("Invalid arguments");return fe(r,t),r}};const Be=new Map;function Fe(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var Ge={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=Fe(e,this._defaultConfig);this._dbInfo=t,Be.has(r)||Be.set(r,new Map)},getItem:function(e,t){e=me(e);const r=this.ready().then(()=>Be.get(this._dbInfo.keyPrefix).get(e));return fe(r,t),r},setItem:function(e,t,r){e=me(e);const n=this.ready().then(()=>(void 0===t&&(t=null),Be.get(this._dbInfo.keyPrefix).set(e,t),t));return fe(n,r),n},removeItem:function(e,t){e=me(e);const r=this.ready().then(()=>{Be.get(this._dbInfo.keyPrefix).delete(e)});return fe(r,t),r},clear:function(e){const t=this.ready().then(()=>{const e=this._dbInfo.keyPrefix;Be.has(e)&&Be.delete(e)});return fe(t,e),t},length:function(e){const t=this.ready().then(()=>Be.get(this._dbInfo.keyPrefix).size);return fe(t,e),t},keys:function(e){const t=this.ready().then(()=>[...Be.get(this._dbInfo.keyPrefix).keys()]);return fe(t,e),t},dropInstance:function(e,t){if(t=Te.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise(t=>{e.storeName?t(Fe(e,this._defaultConfig)):t(`${e.name}/`)}).then(e=>{Be.delete(e)}):Promise.reject("Invalid arguments"),fe(r,t),r}};const ke=(e,t)=>e===t||"number"==typeof e&&"number"==typeof t&&isNaN(e)&&isNaN(t),We=(e,t)=>{const r=e.length;let n=0;for(;n{})}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise(function(t,r){try{const n=e._driver,i=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(i);const s=$e.concat("_initStorage");for(let t=0,n=s.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready));return Ie(r,e,e),r}setDriver(e,t,r){const n=this;Ve(e)||(e=[e]);const i=this._getSupportedDrivers(e);function s(){n._config.driver=n.driver()}function o(e){return n._extend(e),s(),n._ready=n._initStorage(n._config),n._ready}const a=null!==this._driverSet?this._driverSet.catch(()=>Promise.resolve()):Promise.resolve();return this._driverSet=a.then(()=>{const e=i[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then(e=>{n._driver=e._driver,s(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{s();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet}),Ie(this._driverSet,t,r),this._driverSet}supports(e){return!!He[e]}_extend(e){Ze(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let t,r,i,s,o,a,_,c,d,l,E,u,f,I,m,T,C,g,p,y,h=se.btoa,R=se.atob,N=e.bd,v=e.pd,A=e.vm,D=e.hs,S=e.dt,O=e.dm,b=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"],L=!1,M=Promise.resolve(),w=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout(()=>{throw e},0)}})||(()=>{}),U=N&&w||(()=>{}),P=e=>e.join(""),B={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},F=()=>se[P(B.c)][P(B.e)][P(B.f)]("raw",new Uint8Array(B.a.concat(B.b,B.d,B.k)),P(B.g),!0,[P(B.h),P(B.i)]),G=async e=>{if(se[P(B.c)]&&se[P(B.c)][P(B.e)]&&se[P(B.c)][P(B.e)][P(B.f)]){let t=R(e),r=new Uint8Array(t.length);for(let e=0;eR(R(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),W=e=>h(String.fromCharCode(97+25*Math.random())+h(e)).replace(/\+/g,"\n").replace(/=/g," "),V=()=>{if(se.crypto){let e=new Uint8Array(36);se.crypto.getRandomValues(e);let t="";for(let r=0;r<36;++r){let n=e[r]%36;t+=n<10?n:String.fromCharCode(n+87)}return t}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})};const x="Failed to connect to the Dynamsoft License Server: ",H=" Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license.",Y={dlsErrorAndCacheExpire:x+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:x+"network timed out."+H,networkTimeout:x+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:x+"network connection error."+H,failConnect:x+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system date and time, then try again.",idbTimeout:"Failed to open indexedDB: Timeout.",dlsOfflineLicenseExpired:"The DLS2 Offline license has expired. Please contact the site administrator for more information."};let j,J,$,X,K=async()=>{if(j)return j;j=new n,await(async()=>{u||(u=ze)})(),await Promise.race([(async()=>{let e=await u.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise((e,t)=>{setTimeout(()=>t(new Error(Y.idbTimeout)),5e3)})]),I=await u.createInstance({name:"dynamdlsinfo"}),m=h(h("v2")+String.fromCharCode(O.charCodeAt(O.length/2)+1)+h(O));try{let e=await I.getItem(m),t=null;self.indexedDB&&(t=await self.indexedDB.databases());let r=t&&t.some(e=>{if(e)return"dynamltsinfo"===e.name});if(!e&&r){let t=await u.createInstance({name:"dynamltsinfo"});e=await t.getItem(m),e&&await I.setItem(m,e)}e&&([i,l]=JSON.parse(await k(e)))}catch(e){}try{null==i&&(i=V(),I.setItem(m,await W(JSON.stringify([i,null]))))}catch(e){}j.resolve()},Z=async()=>{T=h(String.fromCharCode(D.charCodeAt(0)+10)+h(v)+h(D)+A+h(""+S)),f=await u.createInstance({name:"dynamdlsuns"+h(h("v2"))+h(String.fromCharCode(D.charCodeAt(0)+10)+h(v)+h(D)+A+h(""+S))});try{r=await I.getItem(T)}catch(e){}P=e=>R(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))},Q=async(e,u)=>{if($=Date.now(),J)return J;J=new n;try{let n={pd:v,vm:A,v:t,dt:S||"browser",ed:"javascript",cu:i,ad:O,os:s,fn:o,om:u&&u.om?u.om:[],ic:u&&u.ic?u.ic:{}};c&&(n.rmk=c),D&&(-1!=D.indexOf("-")?n.hs=D:n.og=D);let E={};if(l){let e=await I.getItem(m);e&&([i,l]=JSON.parse(await k(e))),E["lts-time"]=l}_&&(n.sp=_);let f=await Promise.race([(async()=>{let t,s=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");l&&(I.setItem(m,await W(JSON.stringify([i,s]))),l=s);let o="auth/?ext="+encodeURIComponent(h(JSON.stringify(n)));d&&(o+="&"+encodeURIComponent(d));let _,c=!1,u=!1,f=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(_=e,e.errorCode>100&&e.errorCode<200&&(r=null,c=!0,u=!0))}}catch(e){}};try{t=await Promise.race([fetch(b[0]+o,{headers:E,cache:e?"reload":"default",mode:"cors"}),new Promise((e,t)=>setTimeout(t,1e4))]),await f(t)}catch(e){}if(!(r||t&&t.ok||c))try{t=await Promise.race([fetch(b[1]+o,{headers:E,mode:"cors"}),new Promise((e,t)=>setTimeout(t,3e4))]),await f(t)}catch(e){}if(!(r||t&&t.ok||c))try{t=await Promise.race([fetch(b[0]+o,{headers:E,mode:"cors"}),new Promise((e,t)=>setTimeout(t,3e4))]),await f(t)}catch(e){}_&&151==_.errorCode&&(I.removeItem(m),I.removeItem(T),i=V(),n.cu=i,l=void 0,o="auth/?ext="+encodeURIComponent(h(JSON.stringify(n))),t=await Promise.race([fetch(b[0]+o,{headers:E,mode:"cors"}),new Promise((e,t)=>setTimeout(t,3e4))]),await f(t)),(()=>{if(!t||!t.ok){let e;u&&I.setItem(T,""),_?111==_.errorCode?e=_.message:(e=_.message.trim(),e.endsWith(".")||(e+="."),e=a?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=a?Y.publicTrialFailConnect:Y.failConnect;let t=Error(e);throw _&&_.errorCode&&(t.ltsErrorCode=_.errorCode),t}})();let C=await t.text();try{l||(I.setItem(m,await W(JSON.stringify([i,s]))),l=s),I.setItem(T,C)}catch(e){}return C})(),new Promise((e,t)=>{let n;n=a?Y.publicTrialNetworkTimeout:Y.networkTimeout,setTimeout(()=>t(new Error(n)),r?3e3:15e3)})]);r=f}catch(e){N&&console.error(e),E=e}J.resolve(),J=null},z=async()=>{X||(X=(async()=>{if(U(i),!r){if(!L)throw w(E.message),E;return}let e={dm:O};N&&(e.bd=!0),e.brtk=!0,e.ls=b[0],D&&(-1!=D.indexOf("-")?e.hs=D:e.og=D),e.cu=i,o&&(e.fn=o),v&&(e.pd=v),t&&(e.v=t),S&&(e.dt=S),s&&(e.os=s),c&&(e.rmk=c),U(r);try{let t=JSON.parse(await G(r));if(t.pv&&(e.pv=JSON.stringify(t.pv)),t.ba&&(e.ba=t.ba),t.usu&&(e.usu=t.usu),t.trial&&(e.trial=t.trial),t.its&&(e.its=t.its),t.lm&&(e.lm=t.lm),t.mli){const r={};for(let e in t.mli)r[e]=t.mli[e][0];e.ic=r,e.mli=t.mli}t.mlo&&(e.mlo=t.mlo),1==e.trial&&t.msg?e.msg=t.msg:E?e.msg=E.message||E:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!E}catch(e){}U(e);try{await C(e)}catch(e){U("error updl")}await q(),L||(L=!0),X=null})()),await X},q=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await p();if(U(t),t&&t(M=M.then(async()=>{try{let r=await f.keys();if(t||(ee.isFulfilled?e&&(r=r.filter(t=>t{v=e.pd,t=e.v,A=t.split(".")[0],e.dt&&(S=e.dt),D=e.l||"",s="string"!=typeof e.os?JSON.stringify(e.os):e.os,o=e.fn,"string"==typeof o&&(o=o.substring(0,255)),e.ls&&e.ls.length&&(b=e.ls,1==b.length&&b.push(b[0])),a=!D||"200001"===D||D.startsWith("200001-"),_=e.sp,c=e.rmk,"string"==typeof c&&(c=c.substring(0,255)),e.cv&&(d=""+e.cv),C=e.updl,g=e.mnet,p=e.mxet,await K(),await Z(),await Q(),await z(),(!E||E.ltsErrorCode>=102&&E.ltsErrorCode<=120)&&re(null,!0)},i2:async({updl:e,mxet:t,strDLC2:n})=>{C=e,p=t,await K(),P=e=>R(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));let s={pk:n,dm:O};N&&(s.bd=!0),s.cu=i;try{r=n.substring(4);let e=JSON.parse(await G(r));e.pv&&(s.pv=JSON.stringify(e.pv)),e.ba&&(s.ba=e.ba),s.ar=e.in}catch(e){}U(s);try{await C(s)}catch(e){U("error updl")}let o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),a=await p();if(a&&a{let e=new Date;if(e.getTime()<$+36e4)return;let t=e.kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),r=await g(),n=await p();if(n&&nz())}},s:async(e,t,r,n)=>{try{let e=(t=t.trim()).startsWith("{")&&t.endsWith("}")?await(async e=>{if(se[P(B.c)]&&se[P(B.c)][P(B.e)]&&se[P(B.c)][P(B.e)][P(B.f)]){let t=new Uint8Array(e.length);for(let r=0;r{await re()},36e4)},p:ee,u:async()=>(await K(),i),ar:()=>r,pt:()=>a,ae:()=>E,glfd:Q,caul:z}};const et="undefined"==typeof self,tt="function"==typeof importScripts,rt=(()=>{if(!tt){if(!et&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),nt=e=>{if(null==e&&(e="./"),et||tt);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e};ne.engineResourcePaths.dbr={version:"11.0.60-dev-20250812165905",path:rt,isInternal:!0},te.dbr={js:!1,wasm:!0,deps:[Y.MN_DYNAMSOFT_LICENSE,Y.MN_DYNAMSOFT_IMAGE_PROCESSING]};const it="2.0.0";"string"!=typeof ne.engineResourcePaths.std&&g(ne.engineResourcePaths.std.version,it)<0&&(ne.engineResourcePaths.std={version:it,path:nt(rt+`../../dynamsoft-capture-vision-std@${it}/dist/`),isInternal:!0});const st="3.0.10";(!ne.engineResourcePaths.dip||"string"!=typeof ne.engineResourcePaths.dip&&g(ne.engineResourcePaths.dip.version,st)<0)&&(ne.engineResourcePaths.dip={version:st,path:nt(rt+`../../dynamsoft-image-processing@${st}/dist/`),isInternal:!0});BigInt(0),BigInt("0xFFFFFFFEFFFFFFFF"),BigInt(4265345023);const ot=BigInt(3147775),at=BigInt(260096),_t=(BigInt(1),BigInt(2),BigInt(4),BigInt(8),BigInt(16),BigInt(32),BigInt(64),BigInt(128),BigInt(256),BigInt(512),BigInt(1024),BigInt(2048),BigInt(4096),BigInt(8192),BigInt(16384),BigInt(32768),BigInt(65536),BigInt(131072),BigInt(262144)),ct=BigInt(16777216),dt=BigInt(33554432),lt=BigInt(67108864),Et=BigInt(134217728),ut=BigInt(268435456),ft=BigInt(536870912),It=BigInt(1073741824),mt=BigInt(524288),Tt=BigInt(2147483648),Ct=(BigInt(1048576),BigInt(2097152),BigInt(4194304),BigInt(8388608),BigInt(68719476736)),gt=BigInt(0x3f0000000000000),pt=BigInt(4294967296),yt=(BigInt(4503599627370496),BigInt(9007199254740992),BigInt(0x40000000000000),BigInt(0x80000000000000),BigInt(72057594037927940),BigInt(0x200000000000000)),ht=BigInt(8589934592),Rt=BigInt(17179869184),Nt=BigInt(34359738368),vt=BigInt(51539607552),At=BigInt(137438953472),Dt=BigInt(274877906944);var St,Ot,bt,Lt;!function(e){e[e.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",e[e.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",e[e.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(St||(St={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Ot||(Ot={})),function(e){e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=-2147483648]="LM_REV",e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_END=-1]="LM_END"}(bt||(bt={})),function(e){e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e[e.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",e[e.DM_REV=-2147483648]="DM_REV",e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_END=-1]="DM_END"}(Lt||(Lt={}));let Mt,wt,Ut,Pt,Bt,Ft,Gt={},kt={},Wt=[],Vt={};const xt=self,Ht={};xt.coreWorkerVersion="11.0.6000",xt.versions=Ht;const Yt={},jt=xt.waitAsyncDependency=t=>e(void 0,void 0,void 0,function*(){let e="string"==typeof t?[t]:t,r=[];for(let t of e)r.push(Yt[t]=Yt[t]||new n);yield Promise.all(r)}),Jt=(t,r)=>e(void 0,void 0,void 0,function*(){let e,i="string"==typeof t?[t]:t,s=[];for(let t of i){let i;s.push(i=Yt[t]=Yt[t]||new n(e=e||r())),i.isEmpty&&(i.task=e=e||r())}yield Promise.all(s)}),$t=[];xt.setBufferIntoWasm=(e,t=0,r=0,n=0)=>{r&&(e=n?e.subarray(r,n):e.subarray(r));let i=$t[t]=$t[t]||{ptr:0,size:0,maxSize:0};return e.length>i.maxSize&&(i.ptr&&Qt._free(i.ptr),i.ptr=Qt._malloc(e.length),i.maxSize=e.length),Qt.HEAPU8.set(e,i.ptr),i.size=e.length,i.ptr};const Xt={buffer:0,size:0,pos:0,temps:[],needed:0,prepare:function(){if(Xt.needed){for(let e=0;e=Xt.size?(assert(i>0),Xt.needed+=i,r=Qt._malloc(i),Xt.temps.push(r)):(r=Xt.buffer+Xt.pos,Xt.pos+=i),r},copy:function(e,t,r){switch(r>>>=0,t.BYTES_PER_ELEMENT){case 2:r>>>=1;break;case 4:r>>>=2;break;case 8:r>>>=3}for(let n=0;n{let t=intArrayFromString(e),r=Xt.alloc(t,Qt.HEAP8);return Xt.copy(t,Qt.HEAP8,r),r},Qt=xt.Module={print:e=>{xt.bLog&&ir(e)},printErr:e=>{xt.bLog&&ir(e)},locateFile:(e,t)=>{if(["dynamsoft-capture-vision-std.wasm","dynamsoft-core.wasm"].includes(e)){return zt[e.split(".")[0].split("-").at(-1)]+e}return[`${Pt}.wasm`].includes(e)?zt[`${wt.toLowerCase()}Bundle`]+`${Pt}.wasm`:[`${Pt}-ml.wasm`].includes(e)?zt[`${wt.toLowerCase()}Bundle`]+`${Pt}-ml.wasm`:[`${Pt}-ml-simd.wasm`].includes(e)?zt[`${wt.toLowerCase()}Bundle`]+`${Pt}-ml-simd.wasm`:e}},zt=xt.engineResourcePaths={},qt=xt.loadCore=()=>e(void 0,void 0,void 0,function*(){const t="core";yield Jt(t,()=>e(void 0,void 0,void 0,function*(){let e=xt.bLog&&(ir(t+" loading..."),Date.now())||0,r=new Promise(r=>{Qt.onRuntimeInitialized=()=>{Mt=wasmExports,xt.bLog&&ir(t+" initialized, cost "+(Date.now()-e)+" ms"),r(void 0)}});const n=yield(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])))();let i=zt[`${wt.toLowerCase()}Bundle`]+`${Pt}${Bt?"-ml":""}${n&&Ut&&Bt?"-simd":""}.js`;importScripts(i),yield r}));{let e=[];"DCV"===wt?e=["CVR","LICENSE","UTILITY","DIP","DBR","DLR","DDN","DCP"]:"DBR"===wt&&(e=["CVR","LICENSE","DIP","DBR","DCP"]);for(let t of e)Kt(),Mt.emscripten_bind_CoreWasm_PreSetModuleExist(Zt(t)),Kt(),Mt.emscripten_bind_CvrWasm_SetModuleExist(Zt(t),!0);Vt=JSON.parse(UTF8ToString(Mt.emscripten_bind_CoreWasm_GetModuleVersion_0()));for(let e in Vt){const t=e.toLowerCase(),r=xt[`${t}WorkerVersion`];Ht[t]={worker:`${r||"No Worker"}`,wasm:Vt[e]}}}}),er=xt.loadSideModule=(t,{js:r,wasm:n})=>e(void 0,void 0,void 0,function*(){yield Jt(t,()=>e(void 0,void 0,void 0,function*(){yield jt("core")}))}),tr=xt.mapController={loadWasm:(t,r)=>e(void 0,void 0,void 0,function*(){try{Object.assign(zt,t.engineResourcePaths),Ut=t._useSimd,Bt=t._useMLBackend,t.needLoadCore&&(t.bLog&&(xt.bLog=!0),t.dm&&(xt.strDomain=t.dm),t.bd&&(xt.bDebug=!0),wt=t._bundleEnv,Ft="DCV"===wt?zt.dcvData:zt.dbrBundle,Pt="DCV"===wt?"dynamsoft-capture-vision-bundle":"dynamsoft-barcode-reader-bundle",yield qt());for(let e of t.names)yield er(e,t.autoResources[e]);rr(r,{versions:Ht})}catch(e){nr(r,e)}}),setBLog:e=>{xt.bLog=e.value},setBDebug:e=>{xt.bDebug=e.value},getModuleVersion:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=UTF8ToString(Mt.emscripten_bind_CoreWasm_GetModuleVersion_0());rr(r,{versions:JSON.parse(e)})}catch(e){nr(r,e)}}),cfd:(t,r)=>e(void 0,void 0,void 0,function*(){try{Mt.emscripten_bind_CoreWasm_static_CFD_1(t.count),rr(r,{})}catch(e){nr(r,e)}})};addEventListener("message",e=>{const t=e.data?e.data:e,r=t.body,n=t.id,i=t.instanceID,s=tr[t.type];if(!s)throw new Error("Unmatched task: "+t.type);s(r,n,i)});const rr=xt.handleTaskRes=(e,t)=>{postMessage({type:"task",id:e,body:Object.assign({success:!0},t)})},nr=xt.handleTaskErr=(e,t)=>{t||(t={}),postMessage({type:"task",id:e,body:{success:!1,message:t.message||"No error message available.",stack:xt.bDebug&&t.stack||"No stack trace available."}})},ir=xt.log=e=>{postMessage({type:"log",message:e})};let sr,or,ar,_r=null,cr=new Set;self.cvrWorkerVersion="11.0.6000";const dr={},lr=(t,r)=>e(void 0,void 0,void 0,function*(){return dr[t]||(dr[t]=e(void 0,void 0,void 0,function*(){try{let e=0,n=`${r}${t}.data`;const i=yield new Promise((i,s)=>{const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onload=()=>{o.status<200||o.status>=300?i({ok:!1,status:o.status}):i({ok:!0,arrayBuffer:()=>o.response})},o.onerror=o.onabort=()=>{s({ok:!1,status:o.status})},o.onloadstart=()=>{postMessage({type:"event",id:-2,body:{loaded:0,total:e||0,tag:"starting",resourcesPath:r+t+".data"}})},o.onloadend=()=>{postMessage({type:"event",id:-2,body:{loaded:e||0,total:e||0,tag:"completed",resourcesPath:r+t+".data"}})};let a=Date.now();o.onprogress=t=>{if(t.lengthComputable&&(e=t.total),e){const r=Date.now();a+500e(void 0,void 0,void 0,function*(){Kt();const e=JSON.parse(UTF8ToString(Mt.emscripten_bind_CvrWasm_ParseRequiredResources_1(t,Zt(r.templateName))));for(let t=0;te(void 0,void 0,void 0,function*(){Kt();UTF8ToString(Mt.emscripten_bind_CvrWasm_ContainsTask_1(t,Zt(r.templateName))).includes("dlr")&&(yield hr("confusable","ConfusableChars",Ft+"char-resources/"),yield hr("overlapping","OverlappingChars",Ft+"char-resources/"))});function fr(e,t){for(let r of e)if(r.result){if([k.IRUT_BINARY_IMAGE,k.IRUT_COLOUR_IMAGE,k.IRUT_COMPLEMENTED_BARCODE_IMAGE,k.IRUT_ENHANCED_GRAYSCALE_IMAGE,k.IRUT_GRAYSCALE_IMAGE,k.IRUT_SCALED_COLOUR_IMAGE,k.IRUT_SCALED_BARCODE_IMAGE,k.IRUT_TEXTURE_REMOVED_BINARY_IMAGE,k.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE,k.IRUT_TEXT_REMOVED_BINARY_IMAGE,k.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE].includes(BigInt(r.result.unitType))){let e=r.result.imageData.bytes;e&&(e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),r.result.imageData.bytes=e)}else if([k.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE].includes(BigInt(r.result.unitType))){let e=r.result.deformationResistedBarcode.imageData.bytes;e&&(e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),r.result.deformationResistedBarcode.imageData.bytes=e)}else if([k.IRUT_ENHANCED_IMAGE].includes(r.result.unitType)){let e=r.result.enhancedImage.imageData.bytes;e&&(e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),r.result.enhancedImage.imageData.bytes=e)}else if([k.IRUT_CONTOURS].includes(BigInt(r.result.unitType))){let e=r.result.contours,n=r.result.contoursOffset;if(e&&n){e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),n=new Uint8Array(new Uint8Array(t.buffer,n.ptr,n.length));const i=new DataView(e.buffer),s=[];for(let t=0;te(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_CvrWasm_CvrWasm_0();t.loadPresetTemplates&&(zt.dbr&&(sr=yield C(Ft+"templates/DBR-PresetTemplates.json","text"),Kt(),Mt.emscripten_bind_CvrWasm_AppendParameterContent_1(e,Zt(sr))),"DCV"===wt&&(zt.dlr&&(or=yield C(Ft+"templates/DLR-PresetTemplates.json","text"),Kt(),Mt.emscripten_bind_CvrWasm_AppendParameterContent_1(e,Zt(or))),zt.ddn&&(ar=yield C(Ft+"templates/DDN-PresetTemplates.json","text"),Kt(),Mt.emscripten_bind_CvrWasm_AppendParameterContent_1(e,Zt(ar)))),Mt.emscripten_bind_CvrWasm_InitParameter_0(e)),Kt();const n=UTF8ToString(Mt.emscripten_bind_CvrWasm_OutputSettings_1(e,Zt("*"),!1));let i=JSON.parse(UTF8ToString(Mt.emscripten_bind_CoreWasm_GetModuleVersion_0())).CVR;kt=t.itemCountRecord?t.itemCountRecord:{},cr.add(e),rr(r,{instanceID:e,version:i,outputSettings:n})}catch(e){nr(r,e)}}),cvr_appendModelBuffer:(t,r)=>e(void 0,void 0,void 0,function*(){let e;try{e=yield lr(t.modelName,t.path),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}}),cvr_initSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{const i=t.settings;Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_InitSettings_1(n,Zt(i))),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}}),cvr_setCrrRegistry:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{cr.has(n)&&(Kt(),Mt.emscripten_bind_CvrWasm_SetCrrRegistry_1(n,Zt(t.receiver))),rr(r,{success:!0})}catch(e){nr(r,e)}}),cvr_startCapturing:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e=!1;try{Kt();const i=JSON.parse(UTF8ToString(Mt.emscripten_bind_CvrWasm_StartCapturing_1(n,Zt(t.templateName))));if(0!==i.errorCode)throw new Error(`[${i.errorCode}] ${i.errorString}`);yield ur(n,t),Kt();const s=JSON.parse(UTF8ToString(Mt.emscripten_bind_CvrWasm_OutputSettings_1(n,Zt(t.templateName))));if(s&&![0,M.EC_UNSUPPORTED_JSON_KEY_WARNING].includes(s.errorCode))throw new Error(s.errorString);e=1===JSON.parse(s.data).CaptureVisionTemplates[0].OutputOriginalImage,yield Er(n,t),rr(r,{success:!0,isOutputOriginalImage:e})}catch(e){nr(r,e)}}),cvr_parseRequiredResources:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_ParseRequiredResources_1(n,Zt(t.templateName))),rr(r,{success:!0,resources:e})}catch(e){nr(r,e)}}),cvr_clearVerifyList:(e,t,r)=>{try{Mt.emscripten_bind_CvrWasm_ClearVerifyList_0(r),rr(t,{success:!0})}catch(e){nr(t,e)}},cvr_getIntermediateResult:(e,t,r)=>{let n={};try{n=JSON.parse(UTF8ToString(Mt.emscripten_bind_CvrWasm_GetIntermediateResult_0(r)),(e,t)=>["format","possibleFormats","unitType"].includes(e)?BigInt(t):t),n&&fr(n,HEAP8)}catch(e){nr(t,e)}rr(t,{success:!0,result:n})},cvr_setObservedResultUnitTypes:(e,t,r)=>{try{Kt(),Mt.emscripten_bind_CvrWasm_SetObservedResultUnitTypes_1(r,Zt(e.types))}catch(e){nr(t,e)}rr(t,{success:!0})},cvr_getObservedResultUnitTypes:(e,t,r)=>{let n;try{Kt(),n=UTF8ToString(Mt.emscripten_bind_CvrWasm_GetObservedResultUnitTypes_0(r))}catch(e){nr(t,e)}rr(t,{success:!0,result:n})},cvr_isResultUnitTypeObserved:(e,t,r)=>{let n;try{Kt(),n=Mt.emscripten_bind_CvrWasm_IsResultUnitTypeObserved_1(r,Zt(e.type))}catch(e){nr(t,e)}rr(t,{success:!0,result:n})},cvr_capture:(t,r,n)=>e(void 0,void 0,void 0,function*(){let i,s,o;yield checkAndReauth(),ir(`time worker get msg: ${Date.now()}`);try{let e=Date.now();yield Er(n,t),yield ur(n,t),ir("appendResourceTime: "+(Date.now()-e)),_r&&(Mt.emscripten_bind_Destory_CImageData(_r),_r=null),_r=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);let r=Date.now();ir(`start worker capture: ${r}`);const a="DCV"!==wt||t.isScanner;Kt(),s=UTF8ToString(Mt.emscripten_bind_CvrWasm_Capture_4(n,_r,Zt(t.templateName),a,t.dynamsoft));let _=Date.now();if(ir("worker time: "+(_-r)),ir(`end worker capture: ${_}`),s=JSON.parse(s,function(e,t){return"format"!==e||m(this)?t:BigInt(t)}),s.isCheckFailed)throw new Error(`[${s.errorCode}] ${s.errorString}`);let c=Date.now();ir("capture result parsed: "+(c-_));for(let e=0;e["format","possibleFormats","unitType"].includes(e)?BigInt(t):t),i&&fr(i,HEAP8),s.intermediateResult=i;let u=Date.now();ir("get intermediate result: "+(u-E)),ir("after capture handle time: "+(Date.now()-_))}catch(e){return void nr(r,e)}const a=Date.now();ir(`time worker return msg: ${a}`),(t=>{e(void 0,void 0,void 0,function*(){if(Tr.mli){for(let e of t.items)e.type!==b.CRIT_ORIGINAL_IMAGE&&e.type===b.CRIT_BARCODE&&(e.format&ot||e.format&Ct||e.format&ct||e.format&At||e.format&Dt?kt[1]?kt[1]++:kt[1]=1:e.format<||e.format&It?kt[2]?kt[2]++:kt[2]=1:e.format&dt||e.format&mt?kt[3]?kt[3]++:kt[3]=1:e.format&Et?kt[4]?kt[4]++:kt[4]=1:e.format&ut?kt[5]?kt[5]++:kt[5]=1:e.format&ft?kt[6]?kt[6]++:kt[6]=1:e.format&_t?kt[7]?kt[7]++:kt[7]=1:e.format&at?kt[8]?kt[8]++:kt[8]=1:e.format&Tt?kt[9]?kt[9]++:kt[9]=1:e.format>||e.format&yt?kt[10]?kt[10]++:kt[10]=1:e.format&ht?kt[11]?kt[11]++:kt[11]=1:e.format&pt?kt[16]?kt[16]++:kt[16]=1:(e.format&Rt||e.format&Nt||e.format&vt)&&(kt[17]?kt[17]++:kt[17]=1));let e=!1;for(let t in Gt)kt[t]>=Gt[t]&&(Wt.includes(t)||Wt.push(t),kt[t]=0,Gt[t]=void 0,e=!0);e&&(Tr.om?(Tr.om.push(...Wt),Tr.om=[...new Set(Tr.om)]):Tr.om=Wt,yield Ir.glfd(!0,{om:Tr.om,ic:Tr.ic}),yield Ir.caul())}})})(s),postMessage({type:"task",id:r,body:{success:!0,bytes:t.bytes,captureResult:s,workerReturnMsgTime:a,itemCountRecord:kt}},[t.bytes.buffer])}),cvr_outputSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_OutputSettings_1(n,Zt(t.templateName),t.includeDefaultValues)),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}}),cvr_getTemplateNames:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_GetTemplateNames_0(n)),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}}),cvr_getSimplifiedSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_GetSimplifiedSettings_1(n,Zt(t.templateName))),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}}),cvr_updateSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e,i=!1;try{let s=t.settings,o=t.templateName;"object"==typeof s&&s.hasOwnProperty("barcodeSettings")&&(s.barcodeSettings.barcodeFormatIds=s.barcodeSettings.barcodeFormatIds.toString()),Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_UpdateSettings_2(n,Zt(o),Zt(JSON.stringify(s)))),Kt();const a=JSON.parse(UTF8ToString(Mt.emscripten_bind_CvrWasm_OutputSettings_1(n,Zt(o))));if(!a.errorCode){i=1===JSON.parse(a.data).CaptureVisionTemplates[0].OutputOriginalImage}rr(r,{success:!0,response:e,isOutputOriginalImage:i})}catch(e){nr(r,e)}}),cvr_resetSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{Mt.emscripten_bind_CvrWasm_ResetSettings_0(n),Kt(),sr&&Mt.emscripten_bind_CvrWasm_AppendParameterContent_1(n,Zt(sr)),Kt(),or&&Mt.emscripten_bind_CvrWasm_AppendParameterContent_1(n,Zt(or)),Kt(),ar&&Mt.emscripten_bind_CvrWasm_AppendParameterContent_1(n,Zt(ar)),Kt(),e=UTF8ToString(Mt.emscripten_bind_CvrWasm_InitParameter_0(n)),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}}),cvr_cc:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{Kt(),Mt.emscripten_bind_CvrWasm_CC_3(n,Zt(t.text),Zt(t.strFormat),t.isDPM),rr(r,{success:!0})}catch(e){nr(r,e)}}),cvr_getMaxBufferedItems:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=Mt.emscripten_bind_CvrWasm_GetMaxBufferedItems_0(n),rr(r,{success:!0,count:e})}catch(e){nr(r,e)}}),cvr_setMaxBufferedItems:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=Mt.emscripten_bind_CvrWasm_SetMaxBufferedItems_1(n,t.count),rr(r,{success:!0})}catch(e){nr(r,e)}}),cvr_getBufferedCharacterItemSet:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=JSON.parse(UTF8ToString(Mt.emscripten_bind_CvrWasm_GetBufferedCharacterItemSet_0(n)));for(let t of e.items){let e=t.image.bytes;e&&(e=new Uint8Array(new Uint8Array(HEAP8.buffer,e.ptr,e.length)),t.image.bytes=e)}for(let t of e.characterClusters){let e=t.mean.image.bytes;e&&(e=new Uint8Array(new Uint8Array(HEAP8.buffer,e.ptr,e.length)),t.mean.image.bytes=e)}rr(r,{success:!0,itemSet:e})}catch(e){nr(r,e)}}),cvr_setIrrRegistry:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{if(cr.has(n)){Kt(),Mt.emscripten_bind_CvrWasm_SetIrrRegistry_1(n,Zt(JSON.stringify(t.receiverObj))),t.observedResultUnitTypes&&"-1"!==t.observedResultUnitTypes&&(Kt(),Mt.emscripten_bind_CvrWasm_SetObservedResultUnitTypes_1(n,Zt(t.observedResultUnitTypes)));for(let e in t.observedTaskMap)t.observedTaskMap[e]?(Kt(),Mt.emscripten_bind_CvrWasm_AddObservedTask_1(n,Zt(e))):(Kt(),Mt.emscripten_bind_CvrWasm_RemoveObservedTask_1(n,Zt(e)))}rr(r,{success:!0})}catch(e){nr(r,e)}}),cvr_enableResultCrossVerification:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{for(let r in t.verificationEnabled)e=Mt.emscripten_bind_CvrWasm_EnableResultCrossVerification_2(n,Number(r),t.verificationEnabled[r]);rr(r,{success:!0,result:e})}catch(e){nr(r,e)}}),cvr_enableResultDeduplication:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{for(let r in t.duplicateFilterEnabled)e=Mt.emscripten_bind_CvrWasm_EnableResultDeduplication_2(n,Number(r),t.duplicateFilterEnabled[r]);rr(r,{success:!0,result:e})}catch(e){nr(r,e)}}),cvr_setDuplicateForgetTime:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{for(let r in t.duplicateForgetTime)e=Mt.emscripten_bind_CvrWasm_SetDuplicateForgetTime_2(n,Number(r),t.duplicateForgetTime[r]);rr(r,{success:!0,result:e})}catch(e){nr(r,e)}}),cvr_getDuplicateForgetTime:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=Mt.emscripten_bind_CvrWasm_GetDuplicateForgetTime_1(n,t.type),rr(r,{success:!0,time:e})}catch(e){nr(r,e)}}),cvr_containsTask:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{Kt();const e=UTF8ToString(Mt.emscripten_bind_CvrWasm_ContainsTask_1(n,Zt(t.templateName)));rr(r,{success:!0,tasks:e})}catch(e){nr(r,e)}}),cvr_dispose:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{cr.delete(n),Mt.emscripten_bind_Destory_CImageData(_r),_r=null,Mt.emscripten_bind_CvrWasm___destroy___0(n),rr(r,{success:!0})}catch(e){nr(r,e)}}),cvr_getWasmFilterState:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=UTF8ToString(Mt.emscripten_bind_CvrWasm_GetFilterState_0(n)),rr(r,{success:!0,response:e})}catch(e){nr(r,e)}})}),xt.licenseWorkerVersion="11.0.6000";const Cr=t=>e(void 0,void 0,void 0,function*(){try{if(yield jt("core"),t.mli){const e=Gt;for(let r in t.mli){const n=t.mli[r];for(let t=2;t{let e=Qt.getMinExpireTime;return e?e():null},pr=()=>{let e=Qt.getMaxExpireTime;return e?e():null};xt.checkAndReauth=()=>e(void 0,void 0,void 0,function*(){}),Object.assign(tr,{license_dynamsoft:(t,r)=>e(void 0,void 0,void 0,function*(){try{let n,i=t.l,s=t.brtk,o=()=>e(void 0,void 0,void 0,function*(){Ir=Ir||qe({dm:strDomain,log:ir,bd:bDebug}),xt.scsd=Ir.s,t.pd="",t.v="0."+t.v,t.updl=Cr,t.mnet=gr,t.mxet=pr,yield Ir.i(t)}),a=()=>e(void 0,void 0,void 0,function*(){if(i.startsWith("DLC2"))Ir=Ir||qe({dm:strDomain,log:ir,bd:bDebug}),yield Ir.i2({updl:Cr,mxet:pr,strDLC2:i});else{let e={pk:i,dm:strDomain};bDebug&&(e.bd=!0),yield Cr(e)}});s?yield o():yield a(),rr(r,{trial:Tr.trial,ltsErrorCode:n,message:Tr.msg,initLicenseInfo:mr,bSupportDce4Module:Mt.emscripten_bind_CoreWasm_static_GetIsSupportDceModule_0(),bSupportIRTModule:Mt.emscripten_bind_CoreWasm_static_GetIsSupportIRTModule_0()})}catch(e){nr(r,e)}}),license_getDeviceUUID:(t,r)=>e(void 0,void 0,void 0,function*(){try{Ir=Ir||qe({dm:strDomain,log:ir,bd:bDebug});let e=yield Ir.u();rr(r,{uuid:e})}catch(e){nr(r,e)}}),license_getAR:(t,r)=>e(void 0,void 0,void 0,function*(){try{if(Ir){let e={u:yield Ir.u(),pt:Ir.pt()},t=Ir.ar();t&&(e.ar=t);let n=Ir.ae();n&&(e.lem=n.message,e.lec=n.ltsErrorCode),rr(r,e)}else rr(r,null)}catch(e){nr(r,e)}})});let yr={};xt.dlrWorkerVersion="11.0.6000";const hr=xt.checkAndAutoLoadCharsData=(t,r,n)=>e(void 0,void 0,void 0,function*(){if(!yr[r]){let i={ConfusableChars:5561,OverLappingChars:486901}[r];yr[r]=e(void 0,void 0,void 0,function*(){try{let e;const s=n+r+".data",o=yield new Promise((e,t)=>{const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onload=()=>{o.status<200||o.status>=300?e({ok:!1,status:o.status}):e({ok:!0,arrayBuffer:()=>o.response})},o.onerror=o.onabort=()=>{t({ok:!1,status:o.status})},o.onloadstart=()=>{postMessage({type:"event",id:-1,body:{loaded:0,total:i||0,tag:"starting",resourcesPath:n+r+".data"}})},o.onloadend=()=>{postMessage({type:"event",id:-1,body:{loaded:i||0,total:i||0,tag:"completed",resourcesPath:n+r+".data"}})};let a=Date.now();o.onprogress=e=>{if(e.lengthComputable&&(i=e.total),i){const t=Date.now();a+500e(void 0,void 0,void 0,function*(){try{yield hr(t.type,t.dataName,t.dataPath);let e=yield yr[t.dataName];rr(r,{success:!0,result:e})}catch(e){return void nr(r,e)}})}),xt.ddnWorkerVersion="11.0.6000",Object.assign(tr,{ddn_setThresholdValue:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{const e=Mt.emscripten_bind_DdnWasm_0(n);Mt.emscripten_bind_DdnWasm_setThresholdValue_3(e,t.threshold,t.leftLimit,t.rightLimit),rr(r,{success:!0})}catch(e){return void nr(r,e)}})});let Rr=new Map,Nr=new Map;xt.dcpWorkerVersion="11.0.6000";const vr=xt.checkAndAutoLoadResourceBuffer=(t,r)=>e(void 0,void 0,void 0,function*(){if(t=t.toUpperCase(),!Rr.has(t)){let n,i;Rr.set(t,e(void 0,void 0,void 0,function*(){try{n=yield C(r+t+".dcpres","arraybuffer");const e=new Uint8Array(n);i=UTF8ToString(Mt.emscripten_bind_DcpWasm_GetMapNameBySpecification_2(setBufferIntoWasm(e,0),e.length)),i&&!Nr.has(i)&&Nr.set(i,C(r+i,"arraybuffer"));const s=yield Nr.get(i);if(s){const r=new Uint8Array(s);Kt(),ir(UTF8ToString(Mt.emscripten_bind_DcpWasm_AppendResourceBuffer_5(Zt(t+".dcpres"),setBufferIntoWasm(e,0),e.length,setBufferIntoWasm(r,1),r.length)))}else Kt(),ir(UTF8ToString(Mt.emscripten_bind_DcpWasm_AppendResourceBuffer_5(Zt(t+".dcpres"),setBufferIntoWasm(e,0),e.length,null,0)));return!0}catch(e){throw Rr.delete(t),Nr.delete(i),new Error(e)}}))}yield Rr.get(t)});Object.assign(tr,{dcp_appendResourceBuffer:(t,r)=>e(void 0,void 0,void 0,function*(){try{for(let e of t.specificationNames)yield vr(e,t.specificationPath)}catch(e){return void nr(r,e)}rr(r,{success:!0})}),dcp_createInstance:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_DcpWasm_CreateInstance_0();rr(r,{instanceID:e})}catch(e){return void nr(r,e)}}),dcp_dispose:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{Mt.emscripten_bind_DcpWasm___destroy___0(n),rr(r,{success:!0})}catch(e){nr(r,e)}}),dcp_initSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{Kt();let e=UTF8ToString(Mt.emscripten_bind_DcpWasm_InitSettings_1(n,Zt(t.settings)));rr(r,{success:!0,response:e})}catch(e){return void nr(r,e)}}),dcp_resetSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{Mt.emscripten_bind_DcpWasm_ResetSettings_0(n),rr(r,{success:!0})}catch(e){return void nr(r,e)}}),dcp_parse:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{Kt();let e=UTF8ToString(Mt.emscripten_bind_DcpWasm_Parse_3(n,setBufferIntoWasm(t.source,0),t.source.length,Zt(t.taskSettingName)));"parse failed."===e&&(e=JSON.stringify({errorCode:!0,errorString:"parse failed."})),rr(r,{success:!0,parseResponse:e})}catch(e){return void nr(r,e)}})}),xt.utilityWorkerVersion="11.0.6000";const Ar=e=>{let t=e.bytes;t&&(t=new Uint8Array(new Uint8Array(HEAP8.buffer,t.ptr,t.length)),e.bytes=t)};Object.assign(tr,{utility_drawOnImage:(t,r)=>e(void 0,void 0,void 0,function*(){let e;try{let n=Mt.emscripten_bind_Create_CImageData(t.dsImage.bytes.length,setBufferIntoWasm(t.dsImage.bytes,0),t.dsImage.width,t.dsImage.height,t.dsImage.stride,t.dsImage.format,0);const i=t.type.charAt(0).toUpperCase()+t.type.slice(1);Kt(),e=JSON.parse(UTF8ToString(Mt[`emscripten_bind_UtilityWasm_DrawOnImage${i}`](n,Zt(JSON.stringify(t.drawingItem)),t.drawingItem.length,t.color,t.thickness)));let s=e.bytes;s&&(s=new Uint8Array(new Uint8Array(HEAP8.buffer,s.ptr,s.length)),e.bytes=s),Mt.emscripten_bind_Destory_CImageData(n),rr(r,{success:!0,image:e})}catch(e){return void nr(r,e)}}),utility_readFromMemory:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_ReadFromMemory(t.ptr,t.length)));Ar(e),rr(r,{success:!0,imageData:e})}catch(e){return void nr(r,e)}}),utility_saveToMemory:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=UTF8ToString(Mt.emscripten_bind_UtilityWasm_SaveToMemory(e,t.fileFormat));Mt.emscripten_bind_Destory_CImageData(e),rr(r,{success:!0,memery:n})}catch(e){return void nr(r,e)}}),utility_readFromBase64String:(t,r)=>e(void 0,void 0,void 0,function*(){try{Kt();let e=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_ReadFromBase64String(Zt(t.base64String))));Ar(e),rr(r,{success:!0,imageData:e})}catch(e){return void nr(r,e)}}),utility_saveToBase64String:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);Kt();let n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_SaveToBase64String(e,t.fileFormat)));Mt.emscripten_bind_Destory_CImageData(e),rr(r,{success:!0,base64Data:n})}catch(e){return void nr(r,e)}}),utility_cropImage:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);Kt();let n=JSON.parse(UTF8ToString(Mt[`emscripten_bind_UtilityWasm_CropImageFrom${t.type}`](e,Zt(JSON.stringify(t.roi)))));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,cropImage:n})}catch(e){return void nr(r,e)}}),utility_adjustBrightness:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_AdjustBrightness(e,t.brightness)));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,adjustBrightness:n})}catch(e){return void nr(r,e)}}),utility_adjustContrast:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_AdjustContrast(e,t.contrast)));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,adjustContrast:n})}catch(e){return void nr(r,e)}}),utility_filterImage:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_FilterImage(e,t.filterType)));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,filterImage:n})}catch(e){return void nr(r,e)}}),utility_convertToGray:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_ConvertToGray(e,t.R,t.G,t.B)));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,convertToGray:n})}catch(e){return void nr(r,e)}}),utility_convertToBinaryGlobal:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_ConvertToBinaryGlobal(e,t.threshold,t.invert)));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,convertToBinaryGlobal:n})}catch(e){return void nr(r,e)}}),utility_convertToBinaryLocal:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_ConvertToBinaryLocal(e,t.blockSize,t.compensation,t.invert)));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,convertToBinaryLocal:n})}catch(e){return void nr(r,e)}}),utility_cropAndDeskewImage:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=Mt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);Kt();let n=JSON.parse(UTF8ToString(Mt.emscripten_bind_UtilityWasm_CropAndDeskewImage(e,Zt(JSON.stringify(t.roi)))));Mt.emscripten_bind_Destory_CImageData(e),Ar(n),rr(r,{success:!0,cropAndDeskewImage:n})}catch(e){return void nr(r,e)}})})}(); +!function(){"use strict";function e(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{_(n.next(e))}catch(e){s(e)}}function a(e){try{_(n.throw(e))}catch(e){s(e)}}function _(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}_((n=n.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const t=e=>e&&"object"==typeof e&&"function"==typeof e.then,r=(async()=>{})().constructor;class n extends r{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let n;this._task=e,t(e)?n=e:"function"==typeof e&&(n=new r(e)),n&&(async()=>{try{const t=await n;e===this._task&&this.resolve(t)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let r,n;super((e,t)=>{r=e,n=t}),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",r(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}}const i=e=>e&&"object"==typeof e&&"function"==typeof e.then,s=(async()=>{})().constructor;class o extends s{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,i(e)?t=e:"function"==typeof e&&(t=new s(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let t,r;super((e,n)=>{t=e,r=n}),this._s="pending",this.resolve=e=>{this.isPending&&(i(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",r(e))},this.task=e}}var a,_,c;"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.BOPM_BLOCK=0]="BOPM_BLOCK",e[e.BOPM_UPDATE=1]="BOPM_UPDATE"}(a||(a={})),function(e){e[e.CCUT_AUTO=0]="CCUT_AUTO",e[e.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",e[e.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",e[e.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",e[e.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",e[e.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(_||(_={})),function(e){e[e.IPF_BINARY=0]="IPF_BINARY",e[e.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",e[e.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",e[e.IPF_NV21=3]="IPF_NV21",e[e.IPF_RGB_565=4]="IPF_RGB_565",e[e.IPF_RGB_555=5]="IPF_RGB_555",e[e.IPF_RGB_888=6]="IPF_RGB_888",e[e.IPF_ARGB_8888=7]="IPF_ARGB_8888",e[e.IPF_RGB_161616=8]="IPF_RGB_161616",e[e.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",e[e.IPF_ABGR_8888=10]="IPF_ABGR_8888",e[e.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",e[e.IPF_BGR_888=12]="IPF_BGR_888",e[e.IPF_BINARY_8=13]="IPF_BINARY_8",e[e.IPF_NV12=14]="IPF_NV12",e[e.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(c||(c={}));const d="undefined"==typeof self,l="function"==typeof importScripts,E=(()=>{if(!l){if(!d&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),u=e=>{if(null==e&&(e="./"),d||l);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e},f=e=>"number"==typeof e&&!Number.isNaN(e),m=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),I=e=>!(!(e=>!(!m(e)||!f(e.width)||e.width<=0||!f(e.height)||e.height<=0||!f(e.stride)||e.stride<=0||!("format"in e)||"tag"in e&&!p(e.tag)))(e)||!f(e.bytes.length)&&!f(e.bytes.ptr)),p=e=>null===e||!!m(e)&&!!f(e.imageId)&&"type"in e,g=async(e,t,r)=>await new Promise((n,i)=>{let s=new XMLHttpRequest;s.responseType=t,s.onloadstart=()=>{r&&r.loadstartCallback&&r.loadstartCallback()},s.onloadend=async()=>{r&&r.loadendCallback&&r.loadendCallback(),s.status<200||s.status>=300?i(new Error(e+" "+s.status)):n(s.response)},s.onprogress=e=>{r&&r.progressCallback&&r.progressCallback(e)},s.onerror=()=>{i(new Error("Network Error: "+s.statusText))},s.open("GET",e,!0),s.send()}),T=(e,t)=>{let r=e.split("."),n=t.split(".");for(let e=0;e{let e=!1;if(S)try{(await N.getUserMedia({video:!0})).getTracks().forEach(e=>{e.stop()}),e=!0}catch(e){}return e};var b,L,M,w,U,P,B,F,G;"Chrome"===v.browser&&v.version>66||"Safari"===v.browser&&v.version>13||"OPR"===v.browser&&v.version>43||"Edge"===v.browser&&v.version,function(e){e[e.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",e[e.CRIT_BARCODE=2]="CRIT_BARCODE",e[e.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",e[e.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",e[e.CRIT_DESKEWED_IMAGE=16]="CRIT_DESKEWED_IMAGE",e[e.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT",e[e.CRIT_ENHANCED_IMAGE=64]="CRIT_ENHANCED_IMAGE"}(b||(b={})),function(e){e[e.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",e[e.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",e[e.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",e[e.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(L||(L={})),function(e){e[e.EC_OK=0]="EC_OK",e[e.EC_UNKNOWN=-1e4]="EC_UNKNOWN",e[e.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",e[e.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",e[e.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",e[e.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",e[e.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",e[e.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",e[e.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",e[e.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",e[e.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",e[e.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",e[e.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",e[e.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",e[e.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",e[e.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",e[e.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",e[e.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",e[e.EC_TIMEOUT=-10026]="EC_TIMEOUT",e[e.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",e[e.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",e[e.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",e[e.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",e[e.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",e[e.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",e[e.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",e[e.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",e[e.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",e[e.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",e[e.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",e[e.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",e[e.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",e[e.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",e[e.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",e[e.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",e[e.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",e[e.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",e[e.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",e[e.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",e[e.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",e[e.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",e[e.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",e[e.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",e[e.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",e[e.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",e[e.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",e[e.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",e[e.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",e[e.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",e[e.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",e[e.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",e[e.EC_UNSUPPORTED_JSON_KEY_WARNING=-10077]="EC_UNSUPPORTED_JSON_KEY_WARNING",e[e.EC_MODEL_FILE_NOT_FOUND=-10078]="EC_MODEL_FILE_NOT_FOUND",e[e.EC_PDF_LICENSE_NOT_FOUND=-10079]="EC_PDF_LICENSE_NOT_FOUND",e[e.EC_RECT_INVALID=-10080]="EC_RECT_INVALID",e[e.EC_TEMPLATE_VERSION_INCOMPATIBLE=-10081]="EC_TEMPLATE_VERSION_INCOMPATIBLE",e[e.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",e[e.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",e[e.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",e[e.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",e[e.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",e[e.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",e[e.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",e[e.EC_LICENSE_VERSION_NOT_MATCH=-20011]="EC_LICENSE_VERSION_NOT_MATCH",e[e.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",e[e.EC_LICENSE_AUTH_QUOTA_EXCEEDED=-20013]="EC_LICENSE_AUTH_QUOTA_EXCEEDED",e[e.EC_LICENSE_RESULTS_LIMIT_EXCEEDED=-20014]="EC_LICENSE_RESULTS_LIMIT_EXCEEDED",e[e.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",e[e.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",e[e.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",e[e.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",e[e.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",e[e.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",e[e.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",e[e.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",e[e.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",e[e.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",e[e.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",e[e.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",e[e.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",e[e.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",e[e.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",e[e.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(M||(M={})),function(e){e[e.GEM_SKIP=0]="GEM_SKIP",e[e.GEM_AUTO=1]="GEM_AUTO",e[e.GEM_GENERAL=2]="GEM_GENERAL",e[e.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",e[e.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",e[e.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",e[e.GEM_REV=-2147483648]="GEM_REV",e[e.GEM_END=-1]="GEM_END"}(w||(w={})),function(e){e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_AUTO=4]="GTM_AUTO",e[e.GTM_REV=-2147483648]="GTM_REV",e[e.GTM_END=-1]="GTM_END"}(U||(U={})),function(e){e[e.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",e[e.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(P||(P={})),function(e){e[e.PDFRM_VECTOR=1]="PDFRM_VECTOR",e[e.PDFRM_RASTER=2]="PDFRM_RASTER",e[e.PDFRM_REV=-2147483648]="PDFRM_REV"}(B||(B={})),function(e){e[e.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",e[e.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(F||(F={})),function(e){e[e.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",e[e.CVS_PASSED=1]="CVS_PASSED",e[e.CVS_FAILED=2]="CVS_FAILED"}(G||(G={}));const k={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_DESKEWED_IMAGE:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ENHANCED_IMAGE:BigInt(Math.pow(2,30)),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var W,x,V,H,Y,j;!function(e){e[e.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",e[e.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",e[e.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",e[e.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",e[e.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",e[e.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",e[e.ROET_DESKEWED_IMAGE=6]="ROET_DESKEWED_IMAGE",e[e.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",e[e.ROET_TARGET_ROI=8]="ROET_TARGET_ROI",e[e.ROET_ENHANCED_IMAGE=9]="ROET_ENHANCED_IMAGE"}(W||(W={})),function(e){e[e.ST_NULL=0]="ST_NULL",e[e.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",e[e.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",e[e.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",e[e.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",e[e.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",e[e.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",e[e.ST_DOCUMENT_DESKEWING=7]="ST_DOCUMENT_DESKEWING",e[e.ST_IMAGE_ENHANCEMENT=8]="ST_IMAGE_ENHANCEMENT"}(x||(x={})),function(e){e[e.IFF_JPEG=0]="IFF_JPEG",e[e.IFF_PNG=1]="IFF_PNG",e[e.IFF_BMP=2]="IFF_BMP",e[e.IFF_PDF=3]="IFF_PDF"}(V||(V={})),function(e){e[e.ICDM_NEAR=0]="ICDM_NEAR",e[e.ICDM_FAR=1]="ICDM_FAR"}(H||(H={})),function(e){e.MN_DYNAMSOFT_CAPTURE_VISION_ROUTER="cvr",e.MN_DYNAMSOFT_CORE="core",e.MN_DYNAMSOFT_LICENSE="license",e.MN_DYNAMSOFT_IMAGE_PROCESSING="dip",e.MN_DYNAMSOFT_UTILITY="utility",e.MN_DYNAMSOFT_BARCODE_READER="dbr",e.MN_DYNAMSOFT_DOCUMENT_NORMALIZER="ddn",e.MN_DYNAMSOFT_LABEL_RECOGNIZER="dlr",e.MN_DYNAMSOFT_CAPTURE_VISION_DATA="dcvData",e.MN_DYNAMSOFT_NEURAL_NETWORK="dnn",e.MN_DYNAMSOFT_CODE_PARSER="dcp",e.MN_DYNAMSOFT_CAMERA_ENHANCER="dce",e.MN_DYNAMSOFT_CAPTURE_VISION_STD="std"}(Y||(Y={})),function(e){e[e.TMT_LOCAL_TO_ORIGINAL_IMAGE=0]="TMT_LOCAL_TO_ORIGINAL_IMAGE",e[e.TMT_ORIGINAL_TO_LOCAL_IMAGE=1]="TMT_ORIGINAL_TO_LOCAL_IMAGE",e[e.TMT_LOCAL_TO_SECTION_IMAGE=2]="TMT_LOCAL_TO_SECTION_IMAGE",e[e.TMT_SECTION_TO_LOCAL_IMAGE=3]="TMT_SECTION_TO_LOCAL_IMAGE"}(j||(j={}));const J={},$=async e=>{let t="string"==typeof e?[e]:e,r=[];for(let e of t)r.push(J[e]=J[e]||new o);await Promise.all(r)};let X,K=0;const Z=()=>K++,z={};let Q;let q=!1;const ee={},te={dip:{wasm:!0}},re={std:{version:"2.0.0",path:u(E+"../../dynamsoft-capture-vision-std@2.0.0/dist/"),isInternal:!0},core:{version:"4.2.20-dev-20251029130528",path:E,isInternal:!0}};let ne=5;"undefined"!=typeof navigator&&(ne=navigator.hardwareConcurrency?navigator.hardwareConcurrency-1:5),z[-3]=async e=>{ie.onWasmLoadProgressChanged&&ie.onWasmLoadProgressChanged(e.resourcesPath,e.tag,{loaded:e.loaded,total:e.total})};class ie{static get engineResourcePaths(){return re}static set engineResourcePaths(e){Object.assign(re,e)}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(e){(e=>{Q=e,X&&X.postMessage({type:"setBLog",body:{value:!!e}})})(e)}static get _bDebug(){return q}static set _bDebug(e){(e=>{q=e,X&&X.postMessage({type:"setBDebug",body:{value:!!e}})})(e)}static get _workerName(){return`${ie._bundleEnv.toLowerCase()}.bundle.worker.js`}static get wasmLoadOptions(){return ie._wasmLoadOptions}static set wasmLoadOptions(e){Object.assign(ie._wasmLoadOptions,e)}static isModuleLoaded(e){return e=(e=e||"core").toLowerCase(),!!J[e]&&J[e].isFulfilled}static async loadWasm(){return await(async()=>{let e,t;e instanceof Array||(e=e?[e]:[]);let r=J.core;t=!r||r.isEmpty,t||await $("core");let n=new Map;const i=e=>{if(e=e.toLowerCase(),Y.MN_DYNAMSOFT_CAPTURE_VISION_STD==e||Y.MN_DYNAMSOFT_CORE==e)return;let t=te[e].deps;if(null==t?void 0:t.length)for(let e of t)i(e);let r=J[e];n.has(e)||n.set(e,!r||r.isEmpty)};for(let t of e)i(t);let s=[];t&&s.push("core"),s.push(...n.keys());const a=[...n.entries()].filter(e=>!e[1]).map(e=>e[0]);await(async(e,t)=>{let r,n="string"==typeof e?[e]:e,i=[];for(let e of n){let n;i.push(n=J[e]=J[e]||new o(r=r||t())),n.isEmpty&&(n.task=r=r||t())}await Promise.all(i)})(s,async()=>{const e=[...n.entries()].filter(e=>e[1]).map(e=>e[0]);await $(a);const r=(e=>{const t={};for(let r in e){if("rootDirectory"===r)continue;let n=r,i=e[n],s=i&&"object"==typeof i&&i.path?i.path:i,o=e.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof i&&i.isInternal)o&&(s=e[n].version?`${o}${C[n]}@${e[n].version}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`:`${o}${C[n]}/${"dcvData"===n?"":"dist/"}${"ddv"===n?"engine":""}`);else{const r=/^@engineRootDirectory(\/?)/;if("string"==typeof s&&(s=s.replace(r,o||"")),"object"==typeof s&&"dwt"===n){const i=e[n].resourcesPath,s=e[n].serviceInstallerLocation;t[n]={resourcesPath:i.replace(r,o||""),serviceInstallerLocation:s.replace(r,o||"")};continue}}t[n]=u(s)}return t})(re),i={};for(let t of e)i[t]=te[t];const s={engineResourcePaths:r,autoResources:i,names:e,_bundleEnv:ie._bundleEnv,wasmLoadOptions:ie.wasmLoadOptions};let _=new o;if(t){s.needLoadCore=!0;let e=r[`${ie._bundleEnv.toLowerCase()}Bundle`]+ie._workerName;e.startsWith(location.origin)||(e=await fetch(e).then(e=>e.blob()).then(e=>URL.createObjectURL(e))),X=new Worker(e),X.onerror=e=>{let t=new Error(e.message);_.reject(t)},X.addEventListener("message",e=>{let t=e.data?e.data:e,r=t.type,n=t.id,i=t.body;switch(r){case"log":Q&&Q(t.message);break;case"warning":console.warn(t.message);break;case"task":try{z[n](i),delete z[n]}catch(e){throw delete z[n],e}break;case"event":try{z[n](i)}catch(e){throw e}break;default:console.log(e)}}),s.bLog=!!Q,s.bd=q,s.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await $("core");let c=K++;z[c]=e=>{if(e.success)Object.assign(ee,e.versions),"{}"!==JSON.stringify(e.versions)&&(ie._versions=e.versions),ie.loadedWasmType=e.loadedWasmType,_.resolve(void 0);else{const t=Error(e.message);e.stack&&(t.stack=e.stack),_.reject(t)}},X.postMessage({type:"loadWasm",id:c,body:s}),await _})})()}static async detectEnvironment(){return await(async()=>({wasm:A,worker:D,getUserMedia:S,camera:await O(),browser:v.browser,version:v.version,OS:v.OS}))()}static async getModuleVersion(){return await new Promise((e,t)=>{let r=Z();z[r]=async r=>{if(r.success)return e(r.versions);{let e=new Error(r.message);return e.stack=r.stack+"\n"+e.stack,t(e)}},X.postMessage({type:"getModuleVersion",id:r})})}static getVersion(){return`4.2.20-dev-20251029130528(Worker: ${ee.core&&ee.core.worker||"Not Loaded"}, Wasm: ${ee.core&&ee.core.wasm||"Not Loaded"})`}static enableLogging(){ie._onLog=console.log}static disableLogging(){ie._onLog=null}static async cfd(e){return await new Promise((t,r)=>{let n=Z();z[n]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}},X.postMessage({type:"cfd",id:n,body:{count:e}})})}}ie._bSupportDce4Module=-1,ie._bSupportIRTModule=-1,ie._versions=null,ie._bundleEnv="DCV",ie._wasmLoadOptions={wasmType:"auto",pthreadPoolSize:ne},ie.loadedWasmType="ml-simd-pthread",ie.browserInfo=v;const se="undefined"==typeof self,oe=se?{}:self;let ae,_e,ce,de,le;"undefined"!=typeof navigator&&(ae=navigator,_e=ae.userAgent,ce=ae.platform,de=ae.mediaDevices),function(){if(!se){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:ae.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:ce,search:"Win"},Mac:{str:ce},Linux:{str:ce}};let r="unknownBrowser",n=0,i="unknownOS";for(let t in e){const i=e[t]||{};let s=i.str||_e,o=i.search||t,a=i.verStr||_e,_=i.verSearch||t;if(_ instanceof Array||(_=[_]),-1!=s.indexOf(o)){r=t;for(let e of _){let t=a.indexOf(e);if(-1!=t){n=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let n=r.str||_e,s=r.search||e;if(-1!=n.indexOf(s)){i=e;break}}"Linux"==i&&-1!=_e.indexOf("Windows NT")&&(i="HarmonyOS"),le={browser:r,version:n,OS:i}}se&&(le={browser:"ssr",version:0,OS:"ssr"})}(),de&&de.getUserMedia;const Ee="Chrome"===le.browser&&le.version>66||"Safari"===le.browser&&le.version>13||"OPR"===le.browser&&le.version>43||"Edge"===le.browser&&le.version>15;var ue=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function fe(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(i){if("TypeError"!==i.name)throw i;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}}).catch(function(){return!1})}(e).then(function(e){return Ce=e,Ce})}function Ae(e){var t=he[e.name],r={};r.promise=new Promise(function(e,t){r.resolve=e,r.reject=t}),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then(function(){return r.promise}):t.dbReady=r.promise}function De(e){var t=he[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function Se(e,t){var r=he[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function Oe(e,t){return new Promise(function(r,n){if(he[e.name]=he[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);Ae(e),e.db.close()}var i=[e.name];t&&i.push(e.version);var s=ue.open.apply(ue,i);t&&(s.onupgradeneeded=function(t){var r=s.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(Te)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),s.onerror=function(e){e.preventDefault(),n(s.error)},s.onsuccess=function(){var t=s.result;t.onversionchange=function(e){e.target.close()},r(t),De(e)}})}function be(e){return Oe(e,!1)}function Le(e){return Oe(e,!0)}function Me(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),i||r){if(r){var s=e.db.version+1;s>e.version&&(e.version=s)}return!0}return!1}function we(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),i=0;i0&&(!e.db||"InvalidStateError"===i.name||"NotFoundError"===i.name))return Promise.resolve().then(()=>{if(!e.db||"NotFoundError"===i.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),Le(e)}).then(()=>function(e){Ae(e);for(var t=he[e.name],r=t.forages,n=0;n(e.db=t,Me(e)?Le(e):t)).then(n=>{e.db=t.db=n;for(var i=0;i{throw Se(e,t),t})}(e).then(function(){Pe(e,t,r,n-1)})).catch(r);r(i)}}var Be={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var i=he[r.name];i||(i={forages:[],db:null,dbReady:null,deferredOperations:[]},he[r.name]=i),i.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=Ue);var s=[];function o(){return Promise.resolve()}for(var a=0;a{const r=he[e.name],n=r.forages;r.db=t;for(var i=0;i{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;Ae(e);const n=he[e.name],i=n.forages;t.close();for(let e=0;e{const i=ue.open(e.name,r);i.onerror=e=>{i.result.close(),n(e)},i.onupgradeneeded=()=>{i.result.deleteObjectStore(e.storeName)},i.onsuccess=()=>{const e=i.result;e.close(),t(e)}});return s.then(e=>{n.db=e;for(let t=0;t{throw(Se(e,t)||Promise.resolve()).catch(()=>{}),t})}):t.then(t=>{Ae(e);const r=he[e.name],n=r.forages;t.close();for(var i=0;i{var n=ue.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}});return s.then(e=>{r.db=e;for(var t=0;t{throw(Se(e,t)||Promise.resolve()).catch(()=>{}),t})})}else r=Promise.reject("Invalid arguments");return me(r,t),r}};const Fe=new Map;function Ge(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var ke={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=Ge(e,this._defaultConfig);this._dbInfo=t,Fe.has(r)||Fe.set(r,new Map)},getItem:function(e,t){e=pe(e);const r=this.ready().then(()=>Fe.get(this._dbInfo.keyPrefix).get(e));return me(r,t),r},setItem:function(e,t,r){e=pe(e);const n=this.ready().then(()=>(void 0===t&&(t=null),Fe.get(this._dbInfo.keyPrefix).set(e,t),t));return me(n,r),n},removeItem:function(e,t){e=pe(e);const r=this.ready().then(()=>{Fe.get(this._dbInfo.keyPrefix).delete(e)});return me(r,t),r},clear:function(e){const t=this.ready().then(()=>{const e=this._dbInfo.keyPrefix;Fe.has(e)&&Fe.delete(e)});return me(t,e),t},length:function(e){const t=this.ready().then(()=>Fe.get(this._dbInfo.keyPrefix).size);return me(t,e),t},keys:function(e){const t=this.ready().then(()=>[...Fe.get(this._dbInfo.keyPrefix).keys()]);return me(t,e),t},dropInstance:function(e,t){if(t=ge.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise(t=>{e.storeName?t(Ge(e,this._defaultConfig)):t(`${e.name}/`)}).then(e=>{Fe.delete(e)}):Promise.reject("Invalid arguments"),me(r,t),r}};const We=(e,t)=>e===t||"number"==typeof e&&"number"==typeof t&&isNaN(e)&&isNaN(t),xe=(e,t)=>{const r=e.length;let n=0;for(;n{})}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise(function(t,r){try{const n=e._driver,i=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(i);const s=Xe.concat("_initStorage");for(let t=0,n=s.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready));return Ie(r,e,e),r}setDriver(e,t,r){const n=this;Ve(e)||(e=[e]);const i=this._getSupportedDrivers(e);function s(){n._config.driver=n.driver()}function o(e){return n._extend(e),s(),n._ready=n._initStorage(n._config),n._ready}const a=null!==this._driverSet?this._driverSet.catch(()=>Promise.resolve()):Promise.resolve();return this._driverSet=a.then(()=>{const e=i[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then(e=>{n._driver=e._driver,s(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{s();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet}),Ie(this._driverSet,t,r),this._driverSet}supports(e){return!!Ye[e]}_extend(e){ze(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let t,r,i,s,o,a,_,c,d,l,E,u,f,m,I,p,g,T,C,h,y=oe.btoa,R=oe.atob,N=e.bd,v=e.pd,A=e.vm,D=e.hs,S=e.dt,O=e.dm,b=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"],L=!1,M=Promise.resolve(),w=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout(()=>{throw e},0)}})||(()=>{}),U=N&&w||(()=>{}),P=e=>e.join(""),B={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},F=()=>oe[P(B.c)][P(B.e)][P(B.f)]("raw",new Uint8Array(B.a.concat(B.b,B.d,B.k)),P(B.g),!0,[P(B.h),P(B.i)]),G=async e=>{if(oe[P(B.c)]&&oe[P(B.c)][P(B.e)]&&oe[P(B.c)][P(B.e)][P(B.f)]){let t=R(e),r=new Uint8Array(t.length);for(let e=0;eR(R(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),W=e=>y(String.fromCharCode(97+25*Math.random())+y(e)).replace(/\+/g,"\n").replace(/=/g," "),x=()=>{if(oe.crypto){let e=new Uint8Array(36);oe.crypto.getRandomValues(e);let t="";for(let r=0;r<36;++r){let n=e[r]%36;t+=n<10?n:String.fromCharCode(n+87)}return t}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})};const V="Failed to connect to the Dynamsoft License Server: ",H=" Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license.",Y={dlsErrorAndCacheExpire:V+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:V+"network timed out."+H,networkTimeout:V+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:V+"network connection error."+H,failConnect:V+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system date and time, then try again.",idbTimeout:"Failed to open indexedDB: Timeout.",dlsOfflineLicenseExpired:"The DLS2 Offline license has expired. Please contact the site administrator for more information."};let j,J,$,X,K=async()=>{if(j)return j;j=new n,await(async()=>{u||(u=qe)})(),await Promise.race([(async()=>{let e=await u.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise((e,t)=>{setTimeout(()=>t(new Error(Y.idbTimeout)),5e3)})]),m=await u.createInstance({name:"dynamdlsinfo"}),I=y(y("v2")+String.fromCharCode(O.charCodeAt(O.length/2)+1)+y(O));try{let e=await m.getItem(I),t=null;self.indexedDB&&(t=await self.indexedDB.databases());let r=t&&t.some(e=>{if(e)return"dynamltsinfo"===e.name});if(!e&&r){let t=await u.createInstance({name:"dynamltsinfo"});e=await t.getItem(I),e&&await m.setItem(I,e)}e&&([i,l]=JSON.parse(await k(e)))}catch(e){}try{null==i&&(i=x(),m.setItem(I,await W(JSON.stringify([i,null]))))}catch(e){}j.resolve()},Z=async()=>{p=y(String.fromCharCode(D.charCodeAt(0)+10)+y(v)+y(D)+A+y(""+S)),f=await u.createInstance({name:"dynamdlsuns"+y(y("v2"))+y(String.fromCharCode(D.charCodeAt(0)+10)+y(v)+y(D)+A+y(""+S))});try{r=await m.getItem(p)}catch(e){}P=e=>R(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))},z=async(e,u)=>{if($=Date.now(),J)return J;J=new n;try{let n={pd:v,vm:A,v:t,dt:S||"browser",ed:"javascript",cu:i,ad:O,os:s,fn:o,om:u&&u.om?u.om:[],ic:u&&u.ic?u.ic:{}};c&&(n.rmk=c),D&&(-1!=D.indexOf("-")?n.hs=D:n.og=D);let E={};if(l){let e=await m.getItem(I);e&&([i,l]=JSON.parse(await k(e))),E["lts-time"]=l}_&&(n.sp=_);let f=await Promise.race([(async()=>{let t,s=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");l&&(m.setItem(I,await W(JSON.stringify([i,s]))),l=s);let o="auth/?ext="+encodeURIComponent(y(JSON.stringify(n)));d&&(o+="&"+encodeURIComponent(d));let _,c=!1,u=!1,f=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(_=e,e.errorCode>100&&e.errorCode<200&&(r=null,c=!0,u=!0))}}catch(e){}};try{t=await Promise.race([fetch(b[0]+o,{headers:E,cache:e?"reload":"default",mode:"cors"}),new Promise((e,t)=>setTimeout(t,1e4))]),await f(t)}catch(e){}if(!(r||t&&t.ok||c))try{t=await Promise.race([fetch(b[1]+o,{headers:E,mode:"cors"}),new Promise((e,t)=>setTimeout(t,3e4))]),await f(t)}catch(e){}if(!(r||t&&t.ok||c))try{t=await Promise.race([fetch(b[0]+o,{headers:E,mode:"cors"}),new Promise((e,t)=>setTimeout(t,3e4))]),await f(t)}catch(e){}_&&151==_.errorCode&&(m.removeItem(I),m.removeItem(p),i=x(),n.cu=i,l=void 0,o="auth/?ext="+encodeURIComponent(y(JSON.stringify(n))),t=await Promise.race([fetch(b[0]+o,{headers:E,mode:"cors"}),new Promise((e,t)=>setTimeout(t,3e4))]),await f(t)),(()=>{if(!t||!t.ok){let e;u&&m.setItem(p,""),_?111==_.errorCode?e=_.message:(e=_.message.trim(),e.endsWith(".")||(e+="."),e=a?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=a?Y.publicTrialFailConnect:Y.failConnect;let t=Error(e);throw _&&_.errorCode&&(t.ltsErrorCode=_.errorCode),t}})();let g=await t.text();try{l||(m.setItem(I,await W(JSON.stringify([i,s]))),l=s),m.setItem(p,g)}catch(e){}return g})(),new Promise((e,t)=>{let n;n=a?Y.publicTrialNetworkTimeout:Y.networkTimeout,setTimeout(()=>t(new Error(n)),r?3e3:15e3)})]);r=f}catch(e){N&&console.error(e),E=e}J.resolve(),J=null},Q=async()=>{X||(X=(async()=>{if(U(i),!r){if(!L)throw w(E.message),E;return}let e={dm:O};N&&(e.bd=!0),e.brtk=!0,e.ls=b[0],D&&(-1!=D.indexOf("-")?e.hs=D:e.og=D),e.cu=i,o&&(e.fn=o),v&&(e.pd=v),t&&(e.v=t),S&&(e.dt=S),s&&(e.os=s),c&&(e.rmk=c),U(r);try{let t=JSON.parse(await G(r));if(t.pv&&(e.pv=JSON.stringify(t.pv)),t.ba&&(e.ba=t.ba),t.usu&&(e.usu=t.usu),t.trial&&(e.trial=t.trial),t.its&&(e.its=t.its),t.lm&&(e.lm=t.lm),t.mli){const r={};for(let e in t.mli)r[e]=t.mli[e][0];e.ic=r,e.mli=t.mli}t.mlo&&(e.mlo=t.mlo),1==e.trial&&t.msg?e.msg=t.msg:E?e.msg=E.message||E:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!E}catch(e){}U(e);try{await g(e)}catch(e){U("error updl")}await q(),L||(L=!0),X=null})()),await X},q=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await C();if(U(t),t&&t(M=M.then(async()=>{try{let r=await f.keys();if(t||(ee.isFulfilled?e&&(r=r.filter(t=>t{v=e.pd,t=e.v,A=t.split(".")[0],e.dt&&(S=e.dt),D=e.l||"",s="string"!=typeof e.os?JSON.stringify(e.os):e.os,o=e.fn,"string"==typeof o&&(o=o.substring(0,255)),e.ls&&e.ls.length&&(b=e.ls,1==b.length&&b.push(b[0])),a=!D||"200001"===D||D.startsWith("200001-"),_=e.sp,c=e.rmk,"string"==typeof c&&(c=c.substring(0,255)),e.cv&&(d=""+e.cv),g=e.updl,T=e.mnet,C=e.mxet,await K(),await Z(),await z(),await Q(),(!E||E.ltsErrorCode>=102&&E.ltsErrorCode<=120)&&re(null,!0)},i2:async({updl:e,mxet:t,strDLC2:n})=>{g=e,C=t,await K(),P=e=>R(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));let s={pk:n,dm:O};N&&(s.bd=!0),s.cu=i;try{r=n.substring(4);let e=JSON.parse(await G(r));e.pv&&(s.pv=JSON.stringify(e.pv)),e.ba&&(s.ba=e.ba),s.ar=e.in}catch(e){}U(s);try{await g(s)}catch(e){U("error updl")}let o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),a=await C();if(a&&a{let e=new Date;if(e.getTime()<$+36e4)return;let t=e.kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),r=await T(),n=await C();if(n&&nQ())}},s:async(e,t,r,n)=>{try{let e=(t=t.trim()).startsWith("{")&&t.endsWith("}")?await(async e=>{if(oe[P(B.c)]&&oe[P(B.c)][P(B.e)]&&oe[P(B.c)][P(B.e)][P(B.f)]){let t=new Uint8Array(e.length);for(let r=0;r{await re()},36e4)},p:ee,u:async()=>(await K(),i),ar:()=>r,pt:()=>a,ae:()=>E,glfd:z,caul:Q}};const tt="undefined"==typeof self,rt="function"==typeof importScripts,nt=(()=>{if(!rt){if(!tt&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"}})(),it=e=>{if(null==e&&(e="./"),tt||rt);else{let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e};ie.engineResourcePaths.dbr={version:"11.2.20-dev-20251029130556",path:nt,isInternal:!0},te.dbr={js:!1,wasm:!0,deps:[Y.MN_DYNAMSOFT_LICENSE,Y.MN_DYNAMSOFT_IMAGE_PROCESSING]};const st="2.0.0";"string"!=typeof ie.engineResourcePaths.std&&T(ie.engineResourcePaths.std.version,st)<0&&(ie.engineResourcePaths.std={version:st,path:it(nt+`../../dynamsoft-capture-vision-std@${st}/dist/`),isInternal:!0});const ot="3.0.10";(!ie.engineResourcePaths.dip||"string"!=typeof ie.engineResourcePaths.dip&&T(ie.engineResourcePaths.dip.version,ot)<0)&&(ie.engineResourcePaths.dip={version:ot,path:it(nt+`../../dynamsoft-image-processing@${ot}/dist/`),isInternal:!0});BigInt(0),BigInt("0xFFFFFFFEFFFFFFFF"),BigInt(4265345023);const at=BigInt(3147775),_t=BigInt(260096),ct=(BigInt(1),BigInt(2),BigInt(4),BigInt(8),BigInt(16),BigInt(32),BigInt(64),BigInt(128),BigInt(256),BigInt(512),BigInt(1024),BigInt(2048),BigInt(4096),BigInt(8192),BigInt(16384),BigInt(32768),BigInt(65536),BigInt(131072),BigInt(262144)),dt=BigInt(16777216),lt=BigInt(33554432),Et=BigInt(67108864),ut=BigInt(134217728),ft=BigInt(268435456),mt=BigInt(536870912),It=BigInt(1073741824),pt=BigInt(524288),gt=BigInt(2147483648),Tt=(BigInt(1048576),BigInt(2097152),BigInt(4194304),BigInt(8388608),BigInt(68719476736)),Ct=BigInt(0x3f0000000000000),ht=BigInt(4294967296),yt=(BigInt(4503599627370496),BigInt(9007199254740992),BigInt(0x40000000000000),BigInt(0x80000000000000),BigInt(72057594037927940),BigInt(0x200000000000000)),Rt=BigInt(8589934592),Nt=BigInt(17179869184),vt=BigInt(34359738368),At=BigInt(51539607552),Dt=BigInt(137438953472),St=BigInt(274877906944);var Ot,bt,Lt,Mt;!function(e){e[e.EBRT_STANDARD_RESULT=0]="EBRT_STANDARD_RESULT",e[e.EBRT_CANDIDATE_RESULT=1]="EBRT_CANDIDATE_RESULT",e[e.EBRT_PARTIAL_RESULT=2]="EBRT_PARTIAL_RESULT"}(Ot||(Ot={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(bt||(bt={})),function(e){e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_NEURAL_NETWORK=512]="LM_NEURAL_NETWORK",e[e.LM_REV=-2147483648]="LM_REV",e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_END=-1]="LM_END"}(Lt||(Lt={})),function(e){e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e[e.DM_NEURAL_NETWORK=512]="DM_NEURAL_NETWORK",e[e.DM_REV=-2147483648]="DM_REV",e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_END=-1]="DM_END"}(Mt||(Mt={}));let wt,Ut,Pt,Bt,Ft,Gt,kt,Wt,xt={},Vt={},Ht=[],Yt={},jt=!1;const Jt=self,$t={};Jt.coreWorkerVersion="11.2.2000",Jt.versions=$t;const Xt={},Kt=Jt.waitAsyncDependency=t=>e(void 0,void 0,void 0,function*(){let e="string"==typeof t?[t]:t,r=[];for(let t of e)r.push(Xt[t]=Xt[t]||new n);yield Promise.all(r)}),Zt=(t,r)=>e(void 0,void 0,void 0,function*(){let e,i="string"==typeof t?[t]:t,s=[];for(let t of i){let i;s.push(i=Xt[t]=Xt[t]||new n(e=e||r())),i.isEmpty&&(i.task=e=e||r())}yield Promise.all(s)}),zt=[];Jt.setBufferIntoWasm=(e,t=0,r=0,n=0)=>{r&&(e=n?e.subarray(r,n):e.subarray(r));let i=zt[t]=zt[t]||{ptr:0,size:0,maxSize:0};return e.length>i.maxSize&&(i.ptr&&tr._free(i.ptr),i.ptr=tr._malloc(e.length),i.maxSize=e.length),tr.HEAPU8.set(e,i.ptr),i.size=e.length,i.ptr};const Qt={buffer:0,size:0,pos:0,temps:[],needed:0,prepare:function(){if(Qt.needed){for(let e=0;e=Qt.size?(assert(i>0),Qt.needed+=i,r=tr._malloc(i),Qt.temps.push(r)):(r=Qt.buffer+Qt.pos,Qt.pos+=i),r},copy:function(e,t,r){switch(r>>>=0,t.BYTES_PER_ELEMENT){case 2:r>>>=1;break;case 4:r>>>=2;break;case 8:r>>>=3}for(let n=0;n{let t=intArrayFromString(e),r=Qt.alloc(t,tr.HEAP8);return Qt.copy(t,tr.HEAP8,r),r},tr=Jt.Module={print:e=>{Jt.bLog&&_r(e)},printErr:e=>{Jt.bLog&&_r(e)},locateFile:(e,t)=>{if(["dynamsoft-capture-vision-std.wasm","dynamsoft-core.wasm"].includes(e)){return rr[e.split(".")[0].split("-").at(-1)]+e}return[`${Ft}.wasm`].includes(e)?rr[`${Bt.toLowerCase()}Bundle`]+`${Ft}.wasm`:[`${Ft}-ml.wasm`].includes(e)?rr[`${Bt.toLowerCase()}Bundle`]+`${Ft}-ml.wasm`:[`${Ft}-ml-simd.wasm`].includes(e)?rr[`${Bt.toLowerCase()}Bundle`]+`${Ft}-ml-simd.wasm`:[`${Ft}-ml-simd-pthread.wasm`].includes(e)?rr[`${Bt.toLowerCase()}Bundle`]+`${Ft}-ml-simd-pthread.wasm`:e}},rr=Jt.engineResourcePaths={},nr=Jt.loadCore=()=>e(void 0,void 0,void 0,function*(){const t="core";yield Zt(t,()=>e(void 0,void 0,void 0,function*(){let e=Jt.bLog&&(_r(t+" loading..."),Date.now())||0,r=new Promise(r=>{tr.onRuntimeInitialized=()=>{wt=wasmExports,Jt.bLog&&_r(t+" initialized, cost "+(Date.now()-e)+" ms"),r(void 0)}});Ut=yield(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])))(),Pt=(()=>{let e="-ml-simd";if("DBR"===Bt){if("ml-simd-pthread"===kt&&Ut&&crossOriginIsolated)e="-ml-simd-pthread";else if("ml-simd"===kt&&Ut)e="-ml-simd";else if("baseline"===kt)e="",jt=!0;else if("auto"===kt){const t=["iPhone","Mac"].includes(le.OS);Ut&&crossOriginIsolated?e=t?"-ml-simd":"-ml-simd-pthread":Ut&&!crossOriginIsolated?e="-ml-simd":Ut||(e="",jt=!0)}}else if("ml-simd-pthread"===kt&&Ut&&crossOriginIsolated)e="-ml-simd-pthread";else if("ml-simd"===kt&&Ut)e="-ml-simd";else if("ml"===kt)e="-ml";else if("auto"===kt){const t=["iPhone","Mac"].includes(le.OS);Ut&&crossOriginIsolated?e=t?"-ml-simd":"-ml-simd-pthread":Ut&&!crossOriginIsolated?e="-ml-simd":Ut||(e="-ml")}return e})();let n=Ft+Pt,i=rr[`${Bt.toLowerCase()}Bundle`]+n+".js";tr.mainScriptUrlOrBlob=i,tr.pthreadPoolSize=Wt,_r("import library: "+i),importScripts(i),yield r}));{let e=[];"DCV"===Bt?e=["CVR","LICENSE","UTILITY","DIP","DBR","DLR","DDN","DCP"]:"DBR"===Bt&&(e=["CVR","LICENSE","DIP","DBR","DCP"]);for(let t of e)qt(),wt.emscripten_bind_CoreWasm_PreSetModuleExist(er(t)),qt(),wt.emscripten_bind_CvrWasm_SetModuleExist(er(t),!0);Yt=JSON.parse(UTF8ToString(wt.emscripten_bind_CoreWasm_GetModuleVersion()));for(let e in Yt){const t=e.toLowerCase(),r=Jt[`${t}WorkerVersion`];$t[t]={worker:`${r||"No Worker"}`,wasm:Yt[e]}}}}),ir=Jt.loadSideModule=(t,{js:r,wasm:n})=>e(void 0,void 0,void 0,function*(){yield Zt(t,()=>e(void 0,void 0,void 0,function*(){yield Kt("core")}))}),sr=Jt.mapController={loadWasm:(t,r)=>e(void 0,void 0,void 0,function*(){try{Object.assign(rr,t.engineResourcePaths),kt=t.wasmLoadOptions.wasmType,Wt=t.wasmLoadOptions.pthreadPoolSize,t.needLoadCore&&(t.bLog&&(Jt.bLog=!0),t.dm&&(Jt.strDomain=t.dm),t.bd&&(Jt.bDebug=!0),Bt=t._bundleEnv,Gt="DCV"===Bt?rr.dcvData:rr.dbrBundle,Ft="DCV"===Bt?"dynamsoft-capture-vision-bundle":"dynamsoft-barcode-reader-bundle",yield nr());for(let e of t.names)yield ir(e,t.autoResources[e]);or(r,{versions:$t,loadedWasmType:Pt?Pt.replace("-",""):"baseline"})}catch(e){ar(r,e)}}),setBLog:e=>{Jt.bLog=e.value},setBDebug:e=>{Jt.bDebug=e.value},getModuleVersion:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=UTF8ToString(wt.emscripten_bind_CoreWasm_GetModuleVersion());or(r,{versions:JSON.parse(e)})}catch(e){ar(r,e)}}),cfd:(t,r)=>e(void 0,void 0,void 0,function*(){try{wt.emscripten_bind_CoreWasm_static_CFD(t.count),or(r,{})}catch(e){ar(r,e)}})};addEventListener("message",e=>{const t=e.data?e.data:e,r=t.body,n=t.id,i=t.instanceID,s=sr[t.type];if(!s)throw new Error("Unmatched task: "+t.type);s(r,n,i)});const or=Jt.handleTaskRes=(e,t)=>{postMessage({type:"task",id:e,body:Object.assign({success:!0},t)})},ar=Jt.handleTaskErr=(e,t)=>{t||(t={}),postMessage({type:"task",id:e,body:{success:!1,message:t.message||"No error message available.",stack:Jt.bDebug&&t.stack||"No stack trace available."}})},_r=Jt.log=e=>{postMessage({type:"log",message:e})},cr=Jt.warn=e=>{postMessage({type:"warning",message:e})};let dr,lr,Er,ur=null,fr=new Set;self.cvrWorkerVersion="11.2.2000";let mr={};const Ir=(t,r)=>{jt||mr[t]||(mr[t]=e(void 0,void 0,void 0,function*(){try{let e=0,n=`${r}${t}.data`;const i=yield new Promise((i,s)=>{const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onload=()=>{o.status<200||o.status>=300?i({ok:!1,status:o.status}):i({ok:!0,arrayBuffer:()=>o.response})},o.onerror=o.onabort=()=>{s({ok:!1,status:o.status})},o.onloadstart=()=>{postMessage({type:"event",id:-2,body:{loaded:0,total:e||0,tag:"starting",resourcesPath:r+t+".data"}})},o.onloadend=()=>{postMessage({type:"event",id:-2,body:{loaded:e||0,total:e||0,tag:"completed",resourcesPath:r+t+".data"}})};let a=Date.now();o.onprogress=t=>{if(t.lengthComputable&&(e=t.total),e){const r=Date.now();a+500e(void 0,void 0,void 0,function*(){qt();const e=JSON.parse(UTF8ToString(wt.emscripten_bind_CvrWasm_ParseRequiredResources(t,er(r.templateName))));for(let t=0;te(void 0,void 0,void 0,function*(){qt();UTF8ToString(wt.emscripten_bind_CvrWasm_ContainsTask(t,er(r.templateName))).includes("dlr")&&(Dr("confusable","ConfusableChars",Gt+"char-resources/"),Dr("overlapping","OverlappingChars",Gt+"char-resources/"),yield Promise.all(Object.values(Ar)))});function Tr(e,t){for(let r of e)if(r.result){if([k.IRUT_BINARY_IMAGE,k.IRUT_COLOUR_IMAGE,k.IRUT_COMPLEMENTED_BARCODE_IMAGE,k.IRUT_ENHANCED_GRAYSCALE_IMAGE,k.IRUT_GRAYSCALE_IMAGE,k.IRUT_SCALED_COLOUR_IMAGE,k.IRUT_SCALED_BARCODE_IMAGE,k.IRUT_TEXTURE_REMOVED_BINARY_IMAGE,k.IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE,k.IRUT_TEXT_REMOVED_BINARY_IMAGE,k.IRUT_TRANSOFORMED_GRAYSCALE_IMAGE].includes(BigInt(r.result.unitType))){let e=r.result.imageData.bytes;e&&(e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),r.result.imageData.bytes=e)}else if([k.IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE].includes(BigInt(r.result.unitType))){let e=r.result.deformationResistedBarcode.imageData.bytes;e&&(e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),r.result.deformationResistedBarcode.imageData.bytes=e)}else if([k.IRUT_ENHANCED_IMAGE].includes(r.result.unitType)){let e=r.result.enhancedImage.imageData.bytes;e&&(e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),r.result.enhancedImage.imageData.bytes=e)}else if([k.IRUT_CONTOURS].includes(BigInt(r.result.unitType))){let e=r.result.contours,n=r.result.contoursOffset;if(e&&n){e=new Uint8Array(new Uint8Array(t.buffer,e.ptr,e.length)),n=new Uint8Array(new Uint8Array(t.buffer,n.ptr,n.length));const i=new DataView(e.buffer),s=[];for(let t=0;te(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_CvrWasm_CvrWasm();t.loadPresetTemplates&&(rr.dbr&&(dr=yield g(Gt+"templates/DBR-PresetTemplates.json","text"),qt(),wt.emscripten_bind_CvrWasm_AppendParameterContent(e,er(dr))),"DCV"===Bt&&(rr.dlr&&(lr=yield g(Gt+"templates/DLR-PresetTemplates.json","text"),qt(),wt.emscripten_bind_CvrWasm_AppendParameterContent(e,er(lr))),rr.ddn&&(Er=yield g(Gt+"templates/DDN-PresetTemplates.json","text"),qt(),wt.emscripten_bind_CvrWasm_AppendParameterContent(e,er(Er)))),wt.emscripten_bind_CvrWasm_InitParameter(e)),qt();const n=UTF8ToString(wt.emscripten_bind_CvrWasm_OutputSettings(e,er("*"),!1));let i=JSON.parse(UTF8ToString(wt.emscripten_bind_CoreWasm_GetModuleVersion())).CVR;Vt=t.itemCountRecord?t.itemCountRecord:{},fr.add(e),or(r,{instanceID:e,version:i,outputSettings:n,isNoOnnx:jt})}catch(e){ar(r,e)}}),cvr_appendDLModelBuffer:(t,r)=>e(void 0,void 0,void 0,function*(){let e;try{Ir(t.modelName,t.path),e=yield mr[t.modelName],or(r,{success:!0,response:e})}catch(e){ar(r,e)}}),cvr_clearDLModelBuffers:(t,r)=>e(void 0,void 0,void 0,function*(){try{wt.emscripten_bind_CvrWasm_ClearDLModelBuffers(),mr={},or(r,{success:!0})}catch(e){ar(r,e)}}),cvr_initSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{let i=t.settings;if(jt){const e=/"ModelNameArray"\s*:\s*\[[^\]]*\]/g;let t=i.match(e);for(let e of t){let t=JSON.parse(`{${e}}`);if(t.ModelNameArray&&t.ModelNameArray.length>0){cr("Model not supported in the current environment, skipped.");break}}}qt(),e=UTF8ToString(wt.emscripten_bind_CvrWasm_InitSettings(n,er(i))),or(r,{success:!0,response:e})}catch(e){ar(r,e)}}),cvr_setCrrRegistry:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{fr.has(n)&&(qt(),wt.emscripten_bind_CvrWasm_SetCrrRegistry(n,er(t.receiver))),or(r,{success:!0})}catch(e){ar(r,e)}}),cvr_startCapturing:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e=!1;try{qt();const i=JSON.parse(UTF8ToString(wt.emscripten_bind_CvrWasm_StartCapturing(n,er(t.templateName))));if(![0,-90003].includes(i.errorCode))throw new Error(`[${i.errorCode}] ${i.errorString}`);yield gr(n,t),qt();const s=JSON.parse(UTF8ToString(wt.emscripten_bind_CvrWasm_OutputSettings(n,er(t.templateName),!0)));if(s&&![0,M.EC_UNSUPPORTED_JSON_KEY_WARNING].includes(s.errorCode))throw new Error(`[${s.errorCode}] ${s.errorString}`);e=1===JSON.parse(s.data).CaptureVisionTemplates[0].OutputOriginalImage,yield pr(n,t),or(r,{success:!0,isOutputOriginalImage:e})}catch(e){ar(r,e)}}),cvr_parseRequiredResources:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{qt(),e=UTF8ToString(wt.emscripten_bind_CvrWasm_ParseRequiredResources(n,er(t.templateName))),or(r,{success:!0,resources:e})}catch(e){ar(r,e)}}),cvr_clearVerifyList:(e,t,r)=>{try{wt.emscripten_bind_CvrWasm_ClearVerifyList(r),or(t,{success:!0})}catch(e){ar(t,e)}},cvr_getIntermediateResult:(e,t,r)=>{let n={};try{n=JSON.parse(UTF8ToString(wt.emscripten_bind_CvrWasm_GetIntermediateResult(r)),(e,t)=>["format","possibleFormats","unitType"].includes(e)?BigInt(t):t),n&&Tr(n,HEAP8)}catch(e){ar(t,e)}or(t,{success:!0,result:n})},cvr_setObservedResultUnitTypes:(e,t,r)=>{try{qt(),wt.emscripten_bind_CvrWasm_SetObservedResultUnitTypes(r,er(e.types))}catch(e){ar(t,e)}or(t,{success:!0})},cvr_getObservedResultUnitTypes:(e,t,r)=>{let n;try{qt(),n=UTF8ToString(wt.emscripten_bind_CvrWasm_GetObservedResultUnitTypes(r))}catch(e){ar(t,e)}or(t,{success:!0,result:n})},cvr_isResultUnitTypeObserved:(e,t,r)=>{let n;try{qt(),n=wt.emscripten_bind_CvrWasm_IsResultUnitTypeObserved(r,er(e.type))}catch(e){ar(t,e)}or(t,{success:!0,result:n})},cvr_capture:(t,r,n)=>e(void 0,void 0,void 0,function*(){let i,s,o;yield checkAndReauth(),_r(`time worker get msg: ${Date.now()}`);try{let e=Date.now();yield pr(n,t),yield gr(n,t),_r("appendResourceTime: "+(Date.now()-e)),ur&&(wt.emscripten_bind_Destory_CImageData(ur),ur=null),ur=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);let r=Date.now();_r(`start worker capture: ${r}`);const a="DCV"!==Bt||t.isScanner;qt(),s=UTF8ToString(wt.emscripten_bind_CvrWasm_Capture(n,ur,er(t.templateName),a,t.dynamsoft));let _=Date.now();if(_r("worker time: "+(_-r)),_r(`end worker capture: ${_}`),s=JSON.parse(s,function(e,t){return"format"!==e||I(this)?t:BigInt(t)}),s.isCheckFailed)throw new Error(`[${s.errorCode}] ${s.errorString}`);let c=Date.now();_r("capture result parsed: "+(c-_));for(let e=0;e["format","possibleFormats","unitType"].includes(e)?BigInt(t):t),i&&Tr(i,HEAP8),s.intermediateResult=i;let u=Date.now();_r("get intermediate result: "+(u-E)),_r("after capture handle time: "+(Date.now()-_))}catch(e){return void ar(r,e)}const a=Date.now();_r(`time worker return msg: ${a}`),(t=>{e(void 0,void 0,void 0,function*(){if(yr.mli){for(let e of t.items)e.type!==b.CRIT_ORIGINAL_IMAGE&&e.type===b.CRIT_BARCODE&&(e.format&at||e.format&Tt||e.format&dt||e.format&Dt||e.format&St?Vt[1]?Vt[1]++:Vt[1]=1:e.format&Et||e.format&It?Vt[2]?Vt[2]++:Vt[2]=1:e.format<||e.format&pt?Vt[3]?Vt[3]++:Vt[3]=1:e.format&ut?Vt[4]?Vt[4]++:Vt[4]=1:e.format&ft?Vt[5]?Vt[5]++:Vt[5]=1:e.format&mt?Vt[6]?Vt[6]++:Vt[6]=1:e.format&ct?Vt[7]?Vt[7]++:Vt[7]=1:e.format&_t?Vt[8]?Vt[8]++:Vt[8]=1:e.format>?Vt[9]?Vt[9]++:Vt[9]=1:e.format&Ct||e.format&yt?Vt[10]?Vt[10]++:Vt[10]=1:e.format&Rt?Vt[11]?Vt[11]++:Vt[11]=1:e.format&ht?Vt[16]?Vt[16]++:Vt[16]=1:(e.format&Nt||e.format&vt||e.format&At)&&(Vt[17]?Vt[17]++:Vt[17]=1));let e=!1;for(let t in xt)Vt[t]>=xt[t]&&(Ht.includes(t)||Ht.push(t),Vt[t]=0,xt[t]=void 0,e=!0);e&&(yr.om?(yr.om.push(...Ht),yr.om=[...new Set(yr.om)]):yr.om=Ht,yield Cr.glfd(!0,{om:yr.om,ic:yr.ic}),yield Cr.caul())}})})(s),postMessage({type:"task",id:r,body:{success:!0,bytes:t.bytes,captureResult:s,workerReturnMsgTime:a,itemCountRecord:Vt,isScanner:t.isScanner}},[t.bytes.buffer])}),cvr_outputSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{qt(),e=UTF8ToString(wt.emscripten_bind_CvrWasm_OutputSettings(n,er(t.templateName),t.includeDefaultValues)),or(r,{success:!0,response:e})}catch(e){ar(r,e)}}),cvr_setGlobalIntraOpNumThreads:(e,t,r)=>{try{qt(),wt.emscripten_bind_CvrWasm_SetGlobalIntraOpNumThreads(r,e.intraOpNumThreads),or(t,{success:!0})}catch(e){ar(t,e)}},cvr_getTemplateNames:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{qt(),e=UTF8ToString(wt.emscripten_bind_CvrWasm_GetTemplateNames(n)),or(r,{success:!0,response:e})}catch(e){ar(r,e)}}),cvr_getSimplifiedSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{qt(),e=UTF8ToString(wt.emscripten_bind_CvrWasm_GetSimplifiedSettings(n,er(t.templateName))),or(r,{success:!0,response:e})}catch(e){ar(r,e)}}),cvr_updateSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e,i=!1;try{let s=t.settings,o=t.templateName;"object"==typeof s&&s.hasOwnProperty("barcodeSettings")&&(s.barcodeSettings.barcodeFormatIds=s.barcodeSettings.barcodeFormatIds.toString()),qt(),e=UTF8ToString(wt.emscripten_bind_CvrWasm_UpdateSettings(n,er(o),er(JSON.stringify(s)))),qt();const a=JSON.parse(UTF8ToString(wt.emscripten_bind_CvrWasm_OutputSettings(n,er(o))));if(!a.errorCode){i=1===JSON.parse(a.data).CaptureVisionTemplates[0].OutputOriginalImage}or(r,{success:!0,response:e,isOutputOriginalImage:i})}catch(e){ar(r,e)}}),cvr_resetSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{wt.emscripten_bind_CvrWasm_ResetSettings(n),qt(),dr&&wt.emscripten_bind_CvrWasm_AppendParameterContent(n,er(dr)),qt(),lr&&wt.emscripten_bind_CvrWasm_AppendParameterContent(n,er(lr)),qt(),Er&&wt.emscripten_bind_CvrWasm_AppendParameterContent(n,er(Er)),e=UTF8ToString(wt.emscripten_bind_CvrWasm_InitParameter(n)),or(r,{success:!0,response:e})}catch(e){ar(r,e)}}),cvr_cc:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{qt(),wt.emscripten_bind_CvrWasm_CC(n,er(t.text),er(t.strFormat),t.isDPM),or(r,{success:!0})}catch(e){ar(r,e)}}),cvr_getClarity:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{qt(),e=wt.emscripten_bind_CoreWasm_GetClarity(setBufferIntoWasm(t.bytes),t.width,t.height,t.stride,t.bitcount,t.wr,t.hr,t.grayThreshold),or(r,{success:!0,clarity:e})}catch(e){ar(r,e)}}),cvr_getMaxBufferedItems:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=wt.emscripten_bind_CvrWasm_GetMaxBufferedItems(n),or(r,{success:!0,count:e})}catch(e){ar(r,e)}}),cvr_setMaxBufferedItems:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=wt.emscripten_bind_CvrWasm_SetMaxBufferedItems(n,t.count),or(r,{success:!0})}catch(e){ar(r,e)}}),cvr_getBufferedCharacterItemSet:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=JSON.parse(UTF8ToString(wt.emscripten_bind_CvrWasm_GetBufferedCharacterItemSet(n)));for(let t of e.items){let e=t.image.bytes;e&&(e=new Uint8Array(new Uint8Array(HEAP8.buffer,e.ptr,e.length)),t.image.bytes=e)}for(let t of e.characterClusters){let e=t.mean.image.bytes;e&&(e=new Uint8Array(new Uint8Array(HEAP8.buffer,e.ptr,e.length)),t.mean.image.bytes=e)}or(r,{success:!0,itemSet:e})}catch(e){ar(r,e)}}),cvr_setIrrRegistry:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{if(fr.has(n)){qt(),wt.emscripten_bind_CvrWasm_SetIrrRegistry(n,er(JSON.stringify(t.receiverObj))),t.observedResultUnitTypes&&"-1"!==t.observedResultUnitTypes&&(qt(),wt.emscripten_bind_CvrWasm_SetObservedResultUnitTypes(n,er(t.observedResultUnitTypes)));for(let e in t.observedTaskMap)t.observedTaskMap[e]?(qt(),wt.emscripten_bind_CvrWasm_AddObservedTask(n,er(e))):(qt(),wt.emscripten_bind_CvrWasm_RemoveObservedTask(n,er(e)))}or(r,{success:!0})}catch(e){ar(r,e)}}),cvr_enableResultCrossVerification:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{for(let r in t.verificationEnabled)e=wt.emscripten_bind_CvrWasm_EnableResultCrossVerification(n,Number(r),t.verificationEnabled[r]);or(r,{success:!0,result:e})}catch(e){ar(r,e)}}),cvr_enableResultDeduplication:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{for(let r in t.duplicateFilterEnabled)e=wt.emscripten_bind_CvrWasm_EnableResultDeduplication(n,Number(r),t.duplicateFilterEnabled[r]);or(r,{success:!0,result:e})}catch(e){ar(r,e)}}),cvr_setDuplicateForgetTime:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{for(let r in t.duplicateForgetTime)e=wt.emscripten_bind_CvrWasm_SetDuplicateForgetTime(n,Number(r),t.duplicateForgetTime[r]);or(r,{success:!0,result:e})}catch(e){ar(r,e)}}),cvr_getDuplicateForgetTime:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=wt.emscripten_bind_CvrWasm_GetDuplicateForgetTime(n,t.type),or(r,{success:!0,time:e})}catch(e){ar(r,e)}}),cvr_containsTask:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{qt();const e=UTF8ToString(wt.emscripten_bind_CvrWasm_ContainsTask(n,er(t.templateName)));or(r,{success:!0,tasks:e})}catch(e){ar(r,e)}}),cvr_dispose:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{fr.delete(n),wt.emscripten_bind_Destory_CImageData(ur),ur=null,wt.emscripten_bind_CvrWasm___destroy___(n),or(r,{success:!0})}catch(e){ar(r,e)}}),cvr_getWasmFilterState:(t,r,n)=>e(void 0,void 0,void 0,function*(){let e;try{e=UTF8ToString(wt.emscripten_bind_CvrWasm_GetFilterState(n)),or(r,{success:!0,response:e})}catch(e){ar(r,e)}})}),Jt.licenseWorkerVersion="11.2.2000";const Rr=t=>e(void 0,void 0,void 0,function*(){try{if(yield Kt("core"),t.mli){const e=xt;for(let r in t.mli){const n=t.mli[r];for(let t=2;t{let e=tr.getMinExpireTime;return e?e():null},vr=()=>{let e=tr.getMaxExpireTime;return e?e():null};Jt.checkAndReauth=()=>e(void 0,void 0,void 0,function*(){}),Object.assign(sr,{license_dynamsoft:(t,r)=>e(void 0,void 0,void 0,function*(){try{let n,i=t.l,s=t.brtk,o=()=>e(void 0,void 0,void 0,function*(){Cr=Cr||et({dm:strDomain,log:_r,bd:bDebug}),Jt.scsd=Cr.s,t.pd="",t.v="0."+t.v,t.updl=Rr,t.mnet=Nr,t.mxet=vr,yield Cr.i(t)}),a=()=>e(void 0,void 0,void 0,function*(){if(i.startsWith("DLC2"))Cr=Cr||et({dm:strDomain,log:_r,bd:bDebug}),yield Cr.i2({updl:Rr,mxet:vr,strDLC2:i});else{let e={pk:i,dm:strDomain};bDebug&&(e.bd=!0),yield Rr(e)}});s?yield o():yield a(),or(r,{trial:yr.trial,ltsErrorCode:n,message:yr.msg,initLicenseInfo:hr,bSupportDce4Module:wt.emscripten_bind_CoreWasm_static_GetIsSupportDceModule(),bSupportIRTModule:wt.emscripten_bind_CoreWasm_static_GetIsSupportIRTModule()})}catch(e){ar(r,e)}}),license_getDeviceUUID:(t,r)=>e(void 0,void 0,void 0,function*(){try{Cr=Cr||et({dm:strDomain,log:_r,bd:bDebug});let e=yield Cr.u();or(r,{uuid:e})}catch(e){ar(r,e)}}),license_getAR:(t,r)=>e(void 0,void 0,void 0,function*(){try{if(Cr){let e={u:yield Cr.u(),pt:Cr.pt()},t=Cr.ar();t&&(e.ar=t);let n=Cr.ae();n&&(e.lem=n.message,e.lec=n.ltsErrorCode),or(r,e)}else or(r,null)}catch(e){ar(r,e)}})});let Ar={};Jt.dlrWorkerVersion="11.2.2000";const Dr=Jt.checkAndAutoLoadCharsData=(t,r,n)=>{if(!Ar[r]){let i={ConfusableChars:5561,OverLappingChars:486901}[r];Ar[r]=e(void 0,void 0,void 0,function*(){try{let e;const s=n+r+".data",o=yield new Promise((e,t)=>{const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onload=()=>{o.status<200||o.status>=300?e({ok:!1,status:o.status}):e({ok:!0,arrayBuffer:()=>o.response})},o.onerror=o.onabort=()=>{t({ok:!1,status:o.status})},o.onloadstart=()=>{postMessage({type:"event",id:-1,body:{loaded:0,total:i||0,tag:"starting",resourcesPath:n+r+".data"}})},o.onloadend=()=>{postMessage({type:"event",id:-1,body:{loaded:i||0,total:i||0,tag:"completed",resourcesPath:n+r+".data"}})};let a=Date.now();o.onprogress=e=>{if(e.lengthComputable&&(i=e.total),i){const t=Date.now();a+500e(void 0,void 0,void 0,function*(){try{Dr(t.type,t.dataName,t.dataPath);let e=yield Ar[t.dataName];or(r,{success:!0,result:e})}catch(e){return void ar(r,e)}})}),Jt.ddnWorkerVersion="11.2.2000",Object.assign(sr,{ddn_setThresholdValue:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{const e=wt.emscripten_bind_DdnWasm(n);wt.emscripten_bind_DdnWasm_setThresholdValue(e,t.threshold,t.leftLimit,t.rightLimit),or(r,{success:!0})}catch(e){return void ar(r,e)}})});let Sr={},Or={};Jt.dcpWorkerVersion="11.2.2000";const br=Jt.checkAndAutoLoadResourceBuffer=(t,r)=>{if(t=t.toUpperCase(),!Sr[t]){let n,i;Sr[t]=e(void 0,void 0,void 0,function*(){try{let e=r+t+".dcpres",s=0,o=Date.now();n=yield g(e,"arraybuffer",{loadstartCallback:()=>{postMessage({type:"event",id:-4,body:{loaded:0,total:s||0,tag:"starting",resourcesPath:e}})},progressCallback:t=>{if(t.lengthComputable&&(s=t.total),s){const r=Date.now();o+500{postMessage({type:"event",id:-4,body:{loaded:s||0,total:s||0,tag:"completed",resourcesPath:e}})}}):postMessage({type:"event",id:-4,body:{loaded:s||0,total:s||0,tag:"completed",resourcesPath:e}});const _=yield Or[i];if(_){const e=new Uint8Array(_);qt(),_r(UTF8ToString(wt.emscripten_bind_DcpWasm_AppendResourceBuffer(er(t+".dcpres"),setBufferIntoWasm(a,0),a.length,setBufferIntoWasm(e,1),e.length)))}else qt(),_r(UTF8ToString(wt.emscripten_bind_DcpWasm_AppendResourceBuffer(er(t+".dcpres"),setBufferIntoWasm(a,0),a.length,null,0)));return!0}catch(e){throw delete Sr[t],delete Or[i],new Error(e)}})}};Object.assign(sr,{dcp_appendResourceBuffer:(t,r)=>e(void 0,void 0,void 0,function*(){try{for(let e of t.specificationNames)br(e,t.specificationPath);yield Promise.all(Object.values(Sr))}catch(e){return void ar(r,e)}or(r,{success:!0})}),dcp_createInstance:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_DcpWasm_CreateInstance();or(r,{instanceID:e})}catch(e){return void ar(r,e)}}),dcp_dispose:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{wt.emscripten_bind_DcpWasm___destroy___(n),or(r,{success:!0})}catch(e){ar(r,e)}}),dcp_initSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{qt();let e=UTF8ToString(wt.emscripten_bind_DcpWasm_InitSettings(n,er(t.settings)));or(r,{success:!0,response:e})}catch(e){return void ar(r,e)}}),dcp_resetSettings:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{wt.emscripten_bind_DcpWasm_ResetSettings(n),or(r,{success:!0})}catch(e){return void ar(r,e)}}),dcp_parse:(t,r,n)=>e(void 0,void 0,void 0,function*(){try{qt();let e=UTF8ToString(wt.emscripten_bind_DcpWasm_Parse(n,setBufferIntoWasm(t.source,0),t.source.length,er(t.taskSettingName)));"parse failed."===e&&(e=JSON.stringify({errorCode:!0,errorString:"parse failed."})),or(r,{success:!0,parseResponse:e})}catch(e){return void ar(r,e)}})}),Jt.utilityWorkerVersion="11.2.2000";const Lr=e=>{let t=e.bytes;t&&(t=new Uint8Array(new Uint8Array(HEAP8.buffer,t.ptr,t.length)),e.bytes=t)};Object.assign(sr,{utility_drawOnImage:(t,r)=>e(void 0,void 0,void 0,function*(){let e;try{let n=wt.emscripten_bind_Create_CImageData(t.dsImage.bytes.length,setBufferIntoWasm(t.dsImage.bytes,0),t.dsImage.width,t.dsImage.height,t.dsImage.stride,t.dsImage.format,0);const i=t.type.charAt(0).toUpperCase()+t.type.slice(1);qt(),e=JSON.parse(UTF8ToString(wt[`emscripten_bind_UtilityWasm_DrawOnImage${i}`](n,er(JSON.stringify(t.drawingItem)),t.drawingItem.length,t.color,t.thickness)));let s=e.bytes;s&&(s=new Uint8Array(new Uint8Array(HEAP8.buffer,s.ptr,s.length)),e.bytes=s),wt.emscripten_bind_Destory_CImageData(n),or(r,{success:!0,image:e})}catch(e){return void ar(r,e)}}),utility_readFromMemory:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_ReadFromMemory(t.ptr,t.length)));Lr(e),or(r,{success:!0,imageData:e})}catch(e){return void ar(r,e)}}),utility_saveToMemory:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=UTF8ToString(wt.emscripten_bind_UtilityWasm_SaveToMemory(e,t.fileFormat));wt.emscripten_bind_Destory_CImageData(e),or(r,{success:!0,memery:n})}catch(e){return void ar(r,e)}}),utility_readFromBase64String:(t,r)=>e(void 0,void 0,void 0,function*(){try{qt();let e=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_ReadFromBase64String(er(t.base64String))));Lr(e),or(r,{success:!0,imageData:e})}catch(e){return void ar(r,e)}}),utility_saveToBase64String:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);qt();let n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_SaveToBase64String(e,t.fileFormat)));wt.emscripten_bind_Destory_CImageData(e),or(r,{success:!0,base64Data:n})}catch(e){return void ar(r,e)}}),utility_cropImage:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);qt();let n=JSON.parse(UTF8ToString(wt[`emscripten_bind_UtilityWasm_CropImageFrom${t.type}`](e,er(JSON.stringify(t.roi)))));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,cropImage:n})}catch(e){return void ar(r,e)}}),utility_adjustBrightness:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_AdjustBrightness(e,t.brightness)));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,adjustBrightness:n})}catch(e){return void ar(r,e)}}),utility_adjustContrast:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_AdjustContrast(e,t.contrast)));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,adjustContrast:n})}catch(e){return void ar(r,e)}}),utility_filterImage:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_FilterImage(e,t.filterType)));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,filterImage:n})}catch(e){return void ar(r,e)}}),utility_convertToGray:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_ConvertToGray(e,t.R,t.G,t.B)));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,convertToGray:n})}catch(e){return void ar(r,e)}}),utility_convertToBinaryGlobal:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_ConvertToBinaryGlobal(e,t.threshold,t.invert)));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,convertToBinaryGlobal:n})}catch(e){return void ar(r,e)}}),utility_convertToBinaryLocal:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0),n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_ConvertToBinaryLocal(e,t.blockSize,t.compensation,t.invert)));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,convertToBinaryLocal:n})}catch(e){return void ar(r,e)}}),utility_cropAndDeskewImage:(t,r)=>e(void 0,void 0,void 0,function*(){try{let e=wt.emscripten_bind_Create_CImageData(t.bytes.length,setBufferIntoWasm(t.bytes,0),t.width,t.height,t.stride,t.format,0);qt();let n=JSON.parse(UTF8ToString(wt.emscripten_bind_UtilityWasm_CropAndDeskewImage(e,er(JSON.stringify(t.roi)))));wt.emscripten_bind_Destory_CImageData(e),Lr(n),or(r,{success:!0,cropAndDeskewImage:n})}catch(e){return void ar(r,e)}})})}(); diff --git a/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.js b/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.js new file mode 100644 index 0000000..1007a8d --- /dev/null +++ b/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.js @@ -0,0 +1 @@ +function GROWABLE_HEAP_I8(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAP8}function GROWABLE_HEAP_U8(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAPU8}function GROWABLE_HEAP_I16(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAP16}function GROWABLE_HEAP_U16(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAPU16}function GROWABLE_HEAP_I32(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAP32}function GROWABLE_HEAP_U32(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAPU32}function GROWABLE_HEAP_F64(){return wasmMemory.buffer!=HEAP8.buffer&&updateMemoryViews(),HEAPF64}var Module=void 0!==Module?Module:{},moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(e,t)=>{throw t},ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!0,ENVIRONMENT_IS_NODE=!1,ENVIRONMENT_IS_PTHREAD=Module.ENVIRONMENT_IS_PTHREAD||!1,_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;ENVIRONMENT_IS_WORKER&&(_scriptDir=self.location.href);var read_,readAsync,readBinary,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:"undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=0!==scriptDirectory.indexOf("blob:")?scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1):"",read_=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var t=new XMLHttpRequest;t.open("GET",e,!1),t.responseType="arraybuffer";let r=Date.now();return t.onloadstart=()=>{postMessage({type:"event",id:-3,body:{loaded:0,total:pe.lengthComputable?pe.total:0,tag:"starting",resourcesPath:e}})},t.onprogress=t=>{const n=Date.now();r+500{postMessage({type:"event",id:-3,body:{loaded:pe.lengthComputable?pe.total:0,total:pe.lengthComputable?pe.total:0,tag:"completed",resourcesPath:e}})},t.send(null),new Uint8Array(t.response)}),readAsync=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var wasmBinary,out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit),Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,wasmModule,noExitRuntime=Module.noExitRuntime||!0;"object"!=typeof WebAssembly&&abort("no native wasm support detected");var EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,ABORT=!1;function assert(e,t){e||abort(t)}function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e)}var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;if(assert(INITIAL_MEMORY>=20971520,"INITIAL_MEMORY should be larger than STACK_SIZE, was "+INITIAL_MEMORY+"! (STACK_SIZE=20971520)"),ENVIRONMENT_IS_PTHREAD)wasmMemory=Module.wasmMemory;else if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else if(!((wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:32768,shared:!0})).buffer instanceof SharedArrayBuffer))throw err("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),ENVIRONMENT_IS_NODE&&err("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");updateMemoryViews(),INITIAL_MEMORY=wasmMemory.buffer.byteLength;var __ATPRERUN__=[],__ATINIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1,runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function preRun(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,ENVIRONMENT_IS_PTHREAD||(Module.noFSInit||FS.init.initialized||FS.init(),FS.ignorePermissions=!1,TTY.init(),SOCKFS.root=FS.mount(SOCKFS,{},null),callRuntimeCallbacks(__ATINIT__))}function postRun(){if(!ENVIRONMENT_IS_PTHREAD){if(Module.postRun)for("function"==typeof Module.postRun&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(e){return e}function addRunDependency(e){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}function removeRunDependency(e){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}function abort(e){throw Module.onAbort&&Module.onAbort(e),err(e="Aborted("+e+")"),ABORT=!0,EXITSTATUS=1,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}var wasmBinaryFile,tempDouble,tempI64,dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(e){return e.startsWith(dataURIPrefix)}function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(e){return wasmBinary||!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER||"function"!=typeof fetch?Promise.resolve().then(()=>getBinarySync(e)):fetch(e,{credentials:"same-origin"}).then(async t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";postMessage({type:"event",id:-3,body:{total:0,loaded:0,tag:"starting",resourcesPath:e}});const r=+t.headers.get("Content-Length"),n=t.body.getReader();let a=0,o=Date.now();const i=[];for(;;){const{done:t,value:s}=await n.read();if(t)break;if(i.push(s),a+=s.length,r){const t=Date.now();o+500getBinarySync(e))}function instantiateArrayBuffer(e,t,r){return getBinaryPromise(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(r,e=>{err(`failed to asynchronously prepare wasm: ${e}`),abort(e)})}function instantiateAsync(e,t,r,n){return instantiateArrayBuffer(t,r,n)}function createWasm(){var e={env:wasmImports,wasi_snapshot_preview1:wasmImports};function t(e,t){return wasmExports=e.exports,registerTLSInit(wasmExports._emscripten_tls_init),wasmTable=wasmExports.__indirect_function_table,addOnInit(wasmExports.__wasm_call_ctors),exportWasmSymbols(wasmExports),wasmModule=t,removeRunDependency("wasm-instantiate"),wasmExports}if(addRunDependency("wasm-instantiate"),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return err(`Module.instantiateWasm callback failed with error: ${e}`),!1}return instantiateAsync(wasmBinary,wasmBinaryFile,e,function(e){t(e.instance,e.module)}),{}}isDataURI(wasmBinaryFile="dynamsoft-barcode-reader-bundle-ml-simd-pthread.wasm")||(wasmBinaryFile=locateFile(wasmBinaryFile));var ASM_CONSTS={840856:(e,t,r,n)=>{if(void 0===Module||!Module.MountedFiles)return 1;let a=UTF8ToString(e>>>0);a.startsWith("./")&&(a=a.substring(2));const o=Module.MountedFiles.get(a);if(!o)return 2;const i=t>>>0,s=r>>>0,_=n>>>0;if(i+s>o.byteLength)return 3;try{return GROWABLE_HEAP_U8().set(o.subarray(i,i+s),_),0}catch{return 4}}};function ExitStatus(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var terminateWorker=e=>{e.terminate(),e.onmessage=e=>{}},killThread=e=>{var t=PThread.pthreads[e];delete PThread.pthreads[e],terminateWorker(t),__emscripten_thread_free_data(e),PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(t),1),t.pthread_ptr=0},cancelThread=e=>{PThread.pthreads[e].postMessage({cmd:"cancel"})},cleanupThread=e=>{var t=PThread.pthreads[e];assert(t),PThread.returnWorkerToPool(t)},zeroMemory=(e,t)=>(GROWABLE_HEAP_U8().fill(0,e,e+t),e),spawnThread=e=>{var t=PThread.getNewWorker();if(!t)return 6;PThread.runningWorkers.push(t),PThread.pthreads[e.pthread_ptr]=t,t.pthread_ptr=e.pthread_ptr;var r={cmd:"run",start_routine:e.startRoutine,arg:e.arg,pthread_ptr:e.pthread_ptr};return t.postMessage(r,e.transferList),0},PATH={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,n=e.length-1;n>=0;n--){var a=e[n];"."===a?e.splice(n,1):".."===a?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=PATH.isAbs(e),r="/"===e.substr(-1);return(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=PATH.splitPath(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=PATH.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return PATH.normalize(e.join("/"))},join2:(e,t)=>PATH.normalize(e+"/"+t)},initRandomFill=()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>(e.set(crypto.getRandomValues(new Uint8Array(e.byteLength))),e);abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:FS.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,t=PATH.isAbs(n)}return(t?"/":"")+(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=PATH_FS.resolve(e).substr(1),t=PATH_FS.resolve(t).substr(1);for(var n=r(e.split("/")),a=r(t.split("/")),o=Math.min(n.length,a.length),i=o,s=0;s{for(var n=t+r,a=t;e[a]&&!(a>=n);)++a;if(a-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.slice(t,a));for(var o="";t>10,56320|1023&l)}}else o+=String.fromCharCode((31&i)<<6|s)}else o+=String.fromCharCode(i)}return o},FS_stdin_getChar_buffer=[],lengthBytesUTF8=e=>{for(var t=0,r=0;r=55296&&n<=57343?(t+=4,++r):t+=3}return t},stringToUTF8Array=(e,t,r,n)=>{if(!(n>0))return 0;for(var a=r,o=r+n-1,i=0;i=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i);if(s<=127){if(r>=o)break;t[r++]=s}else if(s<=2047){if(r+1>=o)break;t[r++]=192|s>>6,t[r++]=128|63&s}else if(s<=65535){if(r+2>=o)break;t[r++]=224|s>>12,t[r++]=128|s>>6&63,t[r++]=128|63&s}else{if(r+3>=o)break;t[r++]=240|s>>18,t[r++]=128|s>>12&63,t[r++]=128|s>>6&63,t[r++]=128|63&s}}return t[r]=0,r-a};function intArrayFromString(e,t,r){var n=r>0?r:lengthBytesUTF8(e)+1,a=new Array(n),o=stringToUTF8Array(e,a,0,a.length);return t&&(a.length=o),a}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,t){TTY.ttys[e]={input:[],output:[],ops:t},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var t=TTY.ttys[e.node.rdev];if(!t)throw new FS.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,r,n,a){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var o=0,i=0;iFS_stdin_getChar(),put_char(e,t){null===t||10===t?(out(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(out(UTF8ArrayToString(e.output,0)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,r)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(err(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output,0)),e.output=[])}}},alignMemory=(e,t)=>Math.ceil(e/t)*t,mmapAlloc=e=>{e=alignMemory(e,65536);var t=_emscripten_builtin_memalign(65536,e);return t?zeroMemory(t,e):0},MEMFS={ops_table:null,mount:e=>MEMFS.createNode(null,"/",16895,0),createNode(e,t,r,n){if(FS.isBlkdev(r)||FS.isFIFO(r))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var a=FS.createNode(e,t,r,n);return FS.isDir(a.mode)?(a.node_ops=MEMFS.ops_table.dir.node,a.stream_ops=MEMFS.ops_table.dir.stream,a.contents={}):FS.isFile(a.mode)?(a.node_ops=MEMFS.ops_table.file.node,a.stream_ops=MEMFS.ops_table.file.stream,a.usedBytes=0,a.contents=null):FS.isLink(a.mode)?(a.node_ops=MEMFS.ops_table.link.node,a.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(a.mode)&&(a.node_ops=MEMFS.ops_table.chrdev.node,a.stream_ops=MEMFS.ops_table.chrdev.stream),a.timestamp=Date.now(),e&&(e.contents[t]=a,e.timestamp=a.timestamp),a},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var n=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=FS.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,FS.isDir(e.mode)?t.size=4096:FS.isFile(e.mode)?t.size=e.usedBytes:FS.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&MEMFS.resizeFileStorage(e,t.size)},lookup(e,t){throw FS.genericErrors[44]},mknod:(e,t,r,n)=>MEMFS.createNode(e,t,r,n),rename(e,t,r){if(FS.isDir(e.mode)){var n;try{n=FS.lookupNode(t,r)}catch(e){}if(n)for(var a in n.contents)throw new FS.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=FS.lookupNode(e,t);for(var n in r.contents)throw new FS.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var n=MEMFS.createNode(e,t,41471,0);return n.link=r,n},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,n,a){var o=e.node.contents;if(a>=e.node.usedBytes)return 0;var i=Math.min(e.node.usedBytes-a,n);if(i>8&&o.subarray)t.set(o.subarray(a,a+i),r);else for(var s=0;s0||r+t(MEMFS.stream_ops.write(e,t,0,n,r,!1),0)}},asyncLoad=(e,t,r,n)=>{var a=n?"":getUniqueRunDependency(`al ${e}`);readAsync(e,r=>{assert(r,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(r)),a&&removeRunDependency(a)},t=>{if(!r)throw`Loading data file "${e}" failed.`;r()}),a&&addRunDependency(a)},FS_createDataFile=(e,t,r,n,a,o)=>FS.createDataFile(e,t,r,n,a,o),preloadPlugins=Module.preloadPlugins||[],FS_handledByPreloadPlugin=(e,t,r,n)=>{"undefined"!=typeof Browser&&Browser.init();var a=!1;return preloadPlugins.forEach(o=>{a||o.canHandle(t)&&(o.handle(e,t,r,n),a=!0)}),a},FS_createPreloadedFile=(e,t,r,n,a,o,i,s,_,l)=>{var c=t?PATH_FS.resolve(PATH.join2(e,t)):e,u=getUniqueRunDependency(`cp ${c}`);function d(r){function d(r){l&&l(),s||FS_createDataFile(e,t,r,n,a,_),o&&o(),removeRunDependency(u)}FS_handledByPreloadPlugin(r,c,d,()=>{i&&i(),removeRunDependency(u)})||d(r)}addRunDependency(u),"string"==typeof r?asyncLoad(r,e=>d(e),i):d(r)},FS_modeStringToFlags=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t},FS_getMode=(e,t)=>{var r=0;return e&&(r|=365),t&&(r|=146),r},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(!(e=PATH_FS.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new FS.ErrnoError(32);for(var r=e.split("/").filter(e=>!!e),n=FS.root,a="/",o=0;o40)throw new FS.ErrnoError(32)}}return{path:a,node:n}},getPath(e){for(var t;;){if(FS.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?`${r}/${t}`:r+t:r}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var r=0,n=0;n>>0)%FS.nameTable.length},hashAddNode(e){var t=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[t],FS.nameTable[t]=e},hashRemoveNode(e){var t=FS.hashName(e.parent.id,e.name);if(FS.nameTable[t]===e)FS.nameTable[t]=e.name_next;else for(var r=FS.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode(e,t){var r=FS.mayLookup(e);if(r)throw new FS.ErrnoError(r,e);for(var n=FS.hashName(e.id,t),a=FS.nameTable[n];a;a=a.name_next){var o=a.name;if(a.parent.id===e.id&&o===t)return a}return FS.lookup(e,t)},createNode(e,t,r,n){var a=new FS.FSNode(e,t,r,n);return FS.hashAddNode(a),a},destroyNode(e){FS.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>FS.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){var t=FS.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{FS.lookupNode(e,t);return 20}catch(e){}return FS.nodePermissions(e,"wx")},mayDelete(e,t,r){var n;try{n=FS.lookupNode(e,t)}catch(e){return e.errno}var a=FS.nodePermissions(e,"wx");if(a)return a;if(r){if(!FS.isDir(n.mode))return 54;if(FS.isRoot(n)||FS.getPath(n)===FS.cwd())return 10}else if(FS.isDir(n.mode))return 31;return 0},mayOpen:(e,t)=>e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&("r"!==FS.flagsToPermissionString(t)||512&t)?31:FS.nodePermissions(e,FS.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var t=FS.getStream(e);if(!t)throw new FS.ErrnoError(8);return t},getStream:e=>FS.streams[e],createStream:(e,t=-1)=>(FS.FSStream||(FS.FSStream=function(){this.shared={}},FS.FSStream.prototype={},Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new FS.FSStream,e),-1==t&&(t=FS.nextfd()),e.fd=t,FS.streams[t]=e,e),closeStream(e){FS.streams[e]=null},chrdev_stream_ops:{open(e){var t=FS.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){FS.devices[e]={stream_ops:t}},getDevice:e=>FS.devices[e],getMounts(e){for(var t=[],r=[e];r.length;){var n=r.pop();t.push(n),r.push.apply(r,n.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var r=FS.getMounts(FS.root.mount),n=0;function a(e){return FS.syncFSRequests--,t(e)}function o(e){if(e)return o.errored?void 0:(o.errored=!0,a(e));++n>=r.length&&a(null)}r.forEach(t=>{if(!t.type.syncfs)return o(null);t.type.syncfs(t,e,o)})},mount(e,t,r){var n,a="/"===r,o=!r;if(a&&FS.root)throw new FS.ErrnoError(10);if(!a&&!o){var i=FS.lookupPath(r,{follow_mount:!1});if(r=i.path,n=i.node,FS.isMountpoint(n))throw new FS.ErrnoError(10);if(!FS.isDir(n.mode))throw new FS.ErrnoError(54)}var s={type:e,opts:t,mountpoint:r,mounts:[]},_=e.mount(s);return _.mount=s,s.root=_,a?FS.root=_:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),_},unmount(e){var t=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(t.node))throw new FS.ErrnoError(28);var r=t.node,n=r.mounted,a=FS.getMounts(n);Object.keys(FS.nameTable).forEach(e=>{for(var t=FS.nameTable[e];t;){var r=t.name_next;a.includes(t.mount)&&FS.destroyNode(t),t=r}}),r.mounted=null;var o=r.mount.mounts.indexOf(n);r.mount.mounts.splice(o,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,r){var n=FS.lookupPath(e,{parent:!0}).node,a=PATH.basename(e);if(!a||"."===a||".."===a)throw new FS.ErrnoError(28);var o=FS.mayCreate(n,a);if(o)throw new FS.ErrnoError(o);if(!n.node_ops.mknod)throw new FS.ErrnoError(63);return n.node_ops.mknod(n,a,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,FS.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,FS.mknod(e,t,0)),mkdirTree(e,t){for(var r=e.split("/"),n="",a=0;a(void 0===r&&(r=t,t=438),t|=8192,FS.mknod(e,t,r)),symlink(e,t){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var r=FS.lookupPath(t,{parent:!0}).node;if(!r)throw new FS.ErrnoError(44);var n=PATH.basename(t),a=FS.mayCreate(r,n);if(a)throw new FS.ErrnoError(a);if(!r.node_ops.symlink)throw new FS.ErrnoError(63);return r.node_ops.symlink(r,n,e)},rename(e,t){var r,n,a=PATH.dirname(e),o=PATH.dirname(t),i=PATH.basename(e),s=PATH.basename(t);if(r=FS.lookupPath(e,{parent:!0}).node,n=FS.lookupPath(t,{parent:!0}).node,!r||!n)throw new FS.ErrnoError(44);if(r.mount!==n.mount)throw new FS.ErrnoError(75);var _,l=FS.lookupNode(r,i),c=PATH_FS.relative(e,o);if("."!==c.charAt(0))throw new FS.ErrnoError(28);if("."!==(c=PATH_FS.relative(t,a)).charAt(0))throw new FS.ErrnoError(55);try{_=FS.lookupNode(n,s)}catch(e){}if(l!==_){var u=FS.isDir(l.mode),d=FS.mayDelete(r,i,u);if(d)throw new FS.ErrnoError(d);if(d=_?FS.mayDelete(n,s,u):FS.mayCreate(n,s))throw new FS.ErrnoError(d);if(!r.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(l)||_&&FS.isMountpoint(_))throw new FS.ErrnoError(10);if(n!==r&&(d=FS.nodePermissions(r,"w")))throw new FS.ErrnoError(d);FS.hashRemoveNode(l);try{r.node_ops.rename(l,n,s)}catch(e){throw e}finally{FS.hashAddNode(l)}}},rmdir(e){var t=FS.lookupPath(e,{parent:!0}).node,r=PATH.basename(e),n=FS.lookupNode(t,r),a=FS.mayDelete(t,r,!0);if(a)throw new FS.ErrnoError(a);if(!t.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.rmdir(t,r),FS.destroyNode(n)},readdir(e){var t=FS.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new FS.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=FS.lookupPath(e,{parent:!0}).node;if(!t)throw new FS.ErrnoError(44);var r=PATH.basename(e),n=FS.lookupNode(t,r),a=FS.mayDelete(t,r,!1);if(a)throw new FS.ErrnoError(a);if(!t.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.unlink(t,r),FS.destroyNode(n)},readlink(e){var t=FS.lookupPath(e).node;if(!t)throw new FS.ErrnoError(44);if(!t.node_ops.readlink)throw new FS.ErrnoError(28);return PATH_FS.resolve(FS.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var r=FS.lookupPath(e,{follow:!t}).node;if(!r)throw new FS.ErrnoError(44);if(!r.node_ops.getattr)throw new FS.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>FS.stat(e,!0),chmod(e,t,r){var n;"string"==typeof e?n=FS.lookupPath(e,{follow:!r}).node:n=e;if(!n.node_ops.setattr)throw new FS.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&t|-4096&n.mode,timestamp:Date.now()})},lchmod(e,t){FS.chmod(e,t,!0)},fchmod(e,t){var r=FS.getStreamChecked(e);FS.chmod(r.node,t)},chown(e,t,r,n){var a;"string"==typeof e?a=FS.lookupPath(e,{follow:!n}).node:a=e;if(!a.node_ops.setattr)throw new FS.ErrnoError(63);a.node_ops.setattr(a,{timestamp:Date.now()})},lchown(e,t,r){FS.chown(e,t,r,!0)},fchown(e,t,r){var n=FS.getStreamChecked(e);FS.chown(n.node,t,r)},truncate(e,t){if(t<0)throw new FS.ErrnoError(28);var r;"string"==typeof e?r=FS.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(r.mode))throw new FS.ErrnoError(31);if(!FS.isFile(r.mode))throw new FS.ErrnoError(28);var n=FS.nodePermissions(r,"w");if(n)throw new FS.ErrnoError(n);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate(e,t){var r=FS.getStreamChecked(e);if(!(2097155&r.flags))throw new FS.ErrnoError(28);FS.truncate(r.node,t)},utime(e,t,r){var n=FS.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(t,r)})},open(e,t,r){if(""===e)throw new FS.ErrnoError(44);var n;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?FS_modeStringToFlags(t):t)?4095&r|32768:0,"object"==typeof e)n=e;else{e=PATH.normalize(e);try{n=FS.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var a=!1;if(64&t)if(n){if(128&t)throw new FS.ErrnoError(20)}else n=FS.mknod(e,r,0),a=!0;if(!n)throw new FS.ErrnoError(44);if(FS.isChrdev(n.mode)&&(t&=-513),65536&t&&!FS.isDir(n.mode))throw new FS.ErrnoError(54);if(!a){var o=FS.mayOpen(n,t);if(o)throw new FS.ErrnoError(o)}512&t&&!a&&FS.truncate(n,0),t&=-131713;var i=FS.createStream({node:n,path:FS.getPath(n),flags:t,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return i.stream_ops.open&&i.stream_ops.open(i),!Module.logReadFiles||1&t||(FS.readFiles||(FS.readFiles={}),e in FS.readFiles||(FS.readFiles[e]=1)),i},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{FS.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read(e,t,r,n,a){if(n<0||a<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(1==(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var o=void 0!==a;if(o){if(!e.seekable)throw new FS.ErrnoError(70)}else a=e.position;var i=e.stream_ops.read(e,t,r,n,a);return o||(e.position+=i),i},write(e,t,r,n,a,o){if(n<0||a<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&1024&e.flags&&FS.llseek(e,0,2);var i=void 0!==a;if(i){if(!e.seekable)throw new FS.ErrnoError(70)}else a=e.position;var s=e.stream_ops.write(e,t,r,n,a,o);return i||(e.position+=s),s},allocate(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(t<0||r<=0)throw new FS.ErrnoError(28);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap(e,t,r,n,a){if(2&n&&!(2&a)&&2!=(2097155&e.flags))throw new FS.ErrnoError(2);if(1==(2097155&e.flags))throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);return e.stream_ops.mmap(e,t,r,n,a)},msync:(e,t,r,n,a)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,n,a):0,munmap:e=>0,ioctl(e,t,r){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var r,n=FS.open(e,t.flags),a=FS.stat(e).size,o=new Uint8Array(a);return FS.read(n,o,0,a,0),"utf8"===t.encoding?r=UTF8ArrayToString(o,0):"binary"===t.encoding&&(r=o),FS.close(n),r},writeFile(e,t,r={}){r.flags=r.flags||577;var n=FS.open(e,r.flags,r.mode);if("string"==typeof t){var a=new Uint8Array(lengthBytesUTF8(t)+1),o=stringToUTF8Array(t,a,0,a.length);FS.write(n,a,0,o,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");FS.write(n,t,0,t.byteLength,void 0,r.canOwn)}FS.close(n)},cwd:()=>FS.currentPath,chdir(e){var t=FS.lookupPath(e,{follow:!0});if(null===t.node)throw new FS.ErrnoError(44);if(!FS.isDir(t.node.mode))throw new FS.ErrnoError(54);var r=FS.nodePermissions(t.node,"x");if(r)throw new FS.ErrnoError(r);FS.currentPath=t.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(e,t,r,n,a)=>n}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=randomFill(e).byteLength),e[--t]);FS.createDevice("/dev","random",r),FS.createDevice("/dev","urandom",r),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var t=FS.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var r=+t,n=FS.getStreamChecked(r),a={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return a.parent=a,a}},t}},{},"/proc/self/fd")},createStandardStreams(){Module.stdin?FS.createDevice("/dev","stdin",Module.stdin):FS.symlink("/dev/tty","/dev/stdin"),Module.stdout?FS.createDevice("/dev","stdout",null,Module.stdout):FS.symlink("/dev/tty","/dev/stdout"),Module.stderr?FS.createDevice("/dev","stderr",null,Module.stderr):FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},ensureErrnoError(){FS.ErrnoError||(FS.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},FS.ErrnoError.prototype=new Error,FS.ErrnoError.prototype.constructor=FS.ErrnoError,[44].forEach(e=>{FS.genericErrors[e]=new FS.ErrnoError(e),FS.genericErrors[e].stack=""}))},staticInit(){FS.ensureErrnoError(),FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS:MEMFS}},init(e,t,r){FS.init.initialized=!0,FS.ensureErrnoError(),Module.stdin=e||Module.stdin,Module.stdout=t||Module.stdout,Module.stderr=r||Module.stderr,FS.createStandardStreams()},quit(){FS.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},o.prototype.setDataGetter=function(e){this.getter=e},o.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,n=Number(e.getResponseHeader("Content-length")),a=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,o=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,i=1048576;a||(i=n);var s=this;s.setDataGetter(e=>{var t=e*i,a=(e+1)*i-1;if(a=Math.min(a,n-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>n-1)throw new Error("only "+n+" bytes available! programmer error!");var a=new XMLHttpRequest;if(a.open("GET",r,!1),n!==i&&a.setRequestHeader("Range","bytes="+e+"-"+t),a.responseType="arraybuffer",a.overrideMimeType&&a.overrideMimeType("text/plain; charset=x-user-defined"),a.send(null),!(a.status>=200&&a.status<300||304===a.status))throw new Error("Couldn't load "+r+". Status: "+a.status);return void 0!==a.response?new Uint8Array(a.response||[]):intArrayFromString(a.responseText||"",!0)})(t,a)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!o&&n||(i=n=1,n=this.getter(0).length,i=n,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=i,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i=new o;Object.defineProperties(i,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:i}}else s={isDevice:!1,url:r};var _=FS.createFile(e,t,s,n,a);s.contents?_.contents=s.contents:s.url&&(_.contents=null,_.url=s.url),Object.defineProperties(_,{usedBytes:{get:function(){return this.contents.length}}});var l={};function c(e,t,r,n,a){var o=e.node.contents;if(a>=o.length)return 0;var i=Math.min(o.length-a,n);if(o.slice)for(var s=0;s{var t=_.stream_ops[e];l[e]=function(){return FS.forceLoadFile(_),t.apply(null,arguments)}}),l.read=(e,t,r,n,a)=>(FS.forceLoadFile(_),c(e,t,r,n,a)),l.mmap=(e,t,r,n,a)=>{FS.forceLoadFile(_);var o=mmapAlloc(t);if(!o)throw new FS.ErrnoError(48);return c(e,GROWABLE_HEAP_I8(),o,t,r),{ptr:o,allocated:!0}},_.stream_ops=l,_}},UTF8ToString=(e,t)=>e?UTF8ArrayToString(GROWABLE_HEAP_U8(),e,t):"",SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,t,r){if(PATH.isAbs(t))return t;var n;-100===e?n=FS.cwd():n=SYSCALLS.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new FS.ErrnoError(44);return n}return PATH.join2(n,t)},doStat(e,t,r){try{var n=e(t)}catch(e){if(e&&e.node&&PATH.normalize(t)!==PATH.normalize(FS.getPath(e.node)))return-54;throw e}GROWABLE_HEAP_I32()[r>>2]=n.dev,GROWABLE_HEAP_I32()[r+4>>2]=n.mode,GROWABLE_HEAP_U32()[r+8>>2]=n.nlink,GROWABLE_HEAP_I32()[r+12>>2]=n.uid,GROWABLE_HEAP_I32()[r+16>>2]=n.gid,GROWABLE_HEAP_I32()[r+20>>2]=n.rdev,tempI64=[n.size>>>0,(tempDouble=n.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[r+24>>2]=tempI64[0],GROWABLE_HEAP_I32()[r+28>>2]=tempI64[1],GROWABLE_HEAP_I32()[r+32>>2]=4096,GROWABLE_HEAP_I32()[r+36>>2]=n.blocks;var a=n.atime.getTime(),o=n.mtime.getTime(),i=n.ctime.getTime();return tempI64=[Math.floor(a/1e3)>>>0,(tempDouble=Math.floor(a/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[r+40>>2]=tempI64[0],GROWABLE_HEAP_I32()[r+44>>2]=tempI64[1],GROWABLE_HEAP_U32()[r+48>>2]=a%1e3*1e3,tempI64=[Math.floor(o/1e3)>>>0,(tempDouble=Math.floor(o/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[r+56>>2]=tempI64[0],GROWABLE_HEAP_I32()[r+60>>2]=tempI64[1],GROWABLE_HEAP_U32()[r+64>>2]=o%1e3*1e3,tempI64=[Math.floor(i/1e3)>>>0,(tempDouble=Math.floor(i/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[r+72>>2]=tempI64[0],GROWABLE_HEAP_I32()[r+76>>2]=tempI64[1],GROWABLE_HEAP_U32()[r+80>>2]=i%1e3*1e3,tempI64=[n.ino>>>0,(tempDouble=n.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[r+88>>2]=tempI64[0],GROWABLE_HEAP_I32()[r+92>>2]=tempI64[1],0},doMsync(e,t,r,n,a){if(!FS.isFile(t.node.mode))throw new FS.ErrnoError(43);if(2&n)return 0;var o=GROWABLE_HEAP_U8().slice(e,e+r);FS.msync(t,o,a,r,n)},varargs:void 0,get(){var e=GROWABLE_HEAP_I32()[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},getp:()=>SYSCALLS.get(),getStr:e=>UTF8ToString(e),getStreamFromFD:e=>FS.getStreamChecked(e)};function _proc_exit(e){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(0,1,e);EXITSTATUS=e,keepRuntimeAlive()||(PThread.terminateAllThreads(),Module.onExit&&Module.onExit(e),ABORT=!0),quit_(e,new ExitStatus(e))}var exitJS=(e,t)=>{if(EXITSTATUS=e,ENVIRONMENT_IS_PTHREAD)throw exitOnMainThread(e),"unwind";_proc_exit(e)},_exit=exitJS,handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return EXITSTATUS;quit_(1,e)},PThread={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init(){ENVIRONMENT_IS_PTHREAD?PThread.initWorker():PThread.initMainThread()},initMainThread(){for(var e=Module.pthreadPoolSize||5;e--;)PThread.allocateUnusedWorker();addOnPreRun(()=>{addRunDependency("loading-workers"),PThread.loadWasmModuleToAllWorkers(()=>removeRunDependency("loading-workers"))})},initWorker(){PThread.receiveObjectTransfer=PThread.receiveObjectTransfer,PThread.threadInitTLS=PThread.threadInitTLS,PThread.setExitStatus=PThread.setExitStatus,noExitRuntime=!1},setExitStatus:e=>{EXITSTATUS=e},terminateAllThreads__deps:["$terminateWorker"],terminateAllThreads:()=>{for(var e of PThread.runningWorkers)terminateWorker(e);for(var e of PThread.unusedWorkers)terminateWorker(e);PThread.unusedWorkers=[],PThread.runningWorkers=[],PThread.pthreads=[]},returnWorkerToPool:e=>{var t=e.pthread_ptr;delete PThread.pthreads[t],PThread.unusedWorkers.push(e),PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(e),1),e.pthread_ptr=0,__emscripten_thread_free_data(t)},receiveObjectTransfer(e){},threadInitTLS(){PThread.tlsInitFunctions.forEach(e=>e())},loadWasmModuleToWorker:e=>new Promise(t=>{e.onmessage=r=>{var n=r.data,a=n.cmd;if(n.targetThread&&n.targetThread!=_pthread_self()){var o=PThread.pthreads[n.targetThread];o?o.postMessage(n,n.transferList):err(`Internal error! Worker sent a message "${a}" to target pthread ${n.targetThread}, but that thread no longer exists!`)}else"checkMailbox"===a?checkMailbox():"spawnThread"===a?spawnThread(n):"cleanupThread"===a?cleanupThread(n.thread):"killThread"===a?killThread(n.thread):"cancelThread"===a?cancelThread(n.thread):"loaded"===a?(e.loaded=!0,t(e)):"alert"===a?alert(`Thread ${n.threadId}: ${n.text}`):"setimmediate"===n.target?e.postMessage(n):"callHandler"===a?Module[n.handler](...n.args):a&&err(`worker sent an unknown command ${a}`)},e.onerror=e=>{throw err(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r=[];for(var n of["onExit","onAbort","print","printErr"])Module.hasOwnProperty(n)&&r.push(n);e.postMessage({cmd:"load",handlers:r,urlOrBlob:Module.mainScriptUrlOrBlob||_scriptDir,wasmMemory:wasmMemory,wasmModule:wasmModule})}),loadWasmModuleToAllWorkers(e){if(ENVIRONMENT_IS_PTHREAD)return e();Promise.all(PThread.unusedWorkers.map(PThread.loadWasmModuleToWorker)).then(e)},allocateUnusedWorker(){var e,t=locateFile("dynamsoft-barcode-reader-bundle-ml-simd-pthread.worker.js");e=new Worker(t),PThread.unusedWorkers.push(e)},getNewWorker:()=>(0==PThread.unusedWorkers.length&&(PThread.allocateUnusedWorker(),PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0])),PThread.unusedWorkers.pop())};Module.PThread=PThread;var callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},establishStackSpace=()=>{var e=_pthread_self(),t=GROWABLE_HEAP_U32()[e+52>>2],r=GROWABLE_HEAP_U32()[e+56>>2];_emscripten_stack_set_limits(t,t-r),stackRestore(t)};function exitOnMainThread(e){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(1,0,e);_exit(e)}Module.establishStackSpace=establishStackSpace;var wasmTable,asmjsMangle=e=>("__main_argc_argv"==e&&(e="main"),0==e.indexOf("dynCall_")||["stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0"].includes(e)?e:"_"+e),exportWasmSymbols=e=>{for(var t in e){var r=asmjsMangle(t);this[r]=Module[r]=e[t]}},getWasmTableEntry=e=>wasmTable.get(e),invokeEntryPoint=(e,t)=>{!function(e){keepRuntimeAlive()?PThread.setExitStatus(e):__emscripten_thread_exit(e)}(getWasmTableEntry(e)(t))};Module.invokeEntryPoint=invokeEntryPoint;var registerTLSInit=e=>{PThread.tlsInitFunctions.push(e)};function _CreateDirectoryFetcher(){abort("missing function: CreateDirectoryFetcher")}function _DDN_ConvertElement(){abort("missing function: DDN_ConvertElement")}function _DDN_CreateDDNResult(){abort("missing function: DDN_CreateDDNResult")}function _DDN_CreateDDNResultItem(){abort("missing function: DDN_CreateDDNResultItem")}function _DDN_CreateIntermediateResultUnits(){abort("missing function: DDN_CreateIntermediateResultUnits")}function _DDN_CreateParameters(){abort("missing function: DDN_CreateParameters")}function _DDN_CreateTargetRoiDefConditionFilter(){abort("missing function: DDN_CreateTargetRoiDefConditionFilter")}function _DDN_CreateTaskAlgEntity(){abort("missing function: DDN_CreateTaskAlgEntity")}function _DDN_HasSection(){abort("missing function: DDN_HasSection")}function _DDN_ReadTaskSetting(){abort("missing function: DDN_ReadTaskSetting")}function _DLR_ConvertElement(){abort("missing function: DLR_ConvertElement")}function _DLR_CreateBufferedCharacterItemSet(){abort("missing function: DLR_CreateBufferedCharacterItemSet")}function _DLR_CreateIntermediateResultUnits(){abort("missing function: DLR_CreateIntermediateResultUnits")}function _DLR_CreateParameters(){abort("missing function: DLR_CreateParameters")}function _DLR_CreateRecognizedTextLinesResult(){abort("missing function: DLR_CreateRecognizedTextLinesResult")}function _DLR_CreateTargetRoiDefConditionFilter(){abort("missing function: DLR_CreateTargetRoiDefConditionFilter")}function _DLR_CreateTaskAlgEntity(){abort("missing function: DLR_CreateTaskAlgEntity")}function _DLR_CreateTextLineResultItem(){abort("missing function: DLR_CreateTextLineResultItem")}function _DLR_ReadTaskSetting(){abort("missing function: DLR_ReadTaskSetting")}function _DMImage_GetDIB(){abort("missing function: DMImage_GetDIB")}function _DMImage_GetOrientation(){abort("missing function: DMImage_GetOrientation")}function _DeleteDirectoryFetcher(){abort("missing function: DeleteDirectoryFetcher")}function __ZN19LabelRecognizerWasm10getVersionEv(){abort("missing function: _ZN19LabelRecognizerWasm10getVersionEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi")}function __ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb")}function __ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClassC1Ev(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev")}function __ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE(){abort("missing function: _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE")}function __ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE(){abort("missing function: _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE")}function __ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE")}function __ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE")}function __ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE(){abort("missing function: _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE")}function __ZN22DocumentNormalizerWasm10getVersionEv(){abort("missing function: _ZN22DocumentNormalizerWasm10getVersionEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii")}function __ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE")}function __ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev")}function __ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE")}function __ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE")}function __ZN9dynamsoft7utility14CUtilityModule10GetVersionEv(){abort("missing function: _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv")}_CreateDirectoryFetcher.stub=!0,_DDN_ConvertElement.stub=!0,_DDN_CreateDDNResult.stub=!0,_DDN_CreateDDNResultItem.stub=!0,_DDN_CreateIntermediateResultUnits.stub=!0,_DDN_CreateParameters.stub=!0,_DDN_CreateTargetRoiDefConditionFilter.stub=!0,_DDN_CreateTaskAlgEntity.stub=!0,_DDN_HasSection.stub=!0,_DDN_ReadTaskSetting.stub=!0,_DLR_ConvertElement.stub=!0,_DLR_CreateBufferedCharacterItemSet.stub=!0,_DLR_CreateIntermediateResultUnits.stub=!0,_DLR_CreateParameters.stub=!0,_DLR_CreateRecognizedTextLinesResult.stub=!0,_DLR_CreateTargetRoiDefConditionFilter.stub=!0,_DLR_CreateTaskAlgEntity.stub=!0,_DLR_CreateTextLineResultItem.stub=!0,_DLR_ReadTaskSetting.stub=!0,_DMImage_GetDIB.stub=!0,_DMImage_GetOrientation.stub=!0,_DeleteDirectoryFetcher.stub=!0,__ZN19LabelRecognizerWasm10getVersionEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev.stub=!0,__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE.stub=!0,__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE.stub=!0,__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE.stub=!0,__ZN22DocumentNormalizerWasm10getVersionEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev.stub=!0,__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE.stub=!0,__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE.stub=!0,__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv.stub=!0;var ___assert_fail=(e,t,r,n)=>{abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[t?UTF8ToString(t):"unknown filename",r,n?UTF8ToString(n):"unknown function"])},exceptionCaught=[],uncaughtExceptionCount=0,___cxa_begin_catch=e=>{var t=new ExceptionInfo(e);return t.get_caught()||(t.set_caught(!0),uncaughtExceptionCount--),t.set_rethrown(!1),exceptionCaught.push(t),___cxa_increment_exception_refcount(t.excPtr),t.get_exception_ptr()},exceptionLast=0,___cxa_end_catch=()=>{_setThrew(0,0);var e=exceptionCaught.pop();___cxa_decrement_exception_refcount(e.excPtr),exceptionLast=0};function ExceptionInfo(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){GROWABLE_HEAP_U32()[this.ptr+4>>2]=e},this.get_type=function(){return GROWABLE_HEAP_U32()[this.ptr+4>>2]},this.set_destructor=function(e){GROWABLE_HEAP_U32()[this.ptr+8>>2]=e},this.get_destructor=function(){return GROWABLE_HEAP_U32()[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,GROWABLE_HEAP_I8()[this.ptr+12|0]=e},this.get_caught=function(){return 0!=GROWABLE_HEAP_I8()[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,GROWABLE_HEAP_I8()[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=GROWABLE_HEAP_I8()[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){GROWABLE_HEAP_U32()[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return GROWABLE_HEAP_U32()[this.ptr+16>>2]},this.get_exception_ptr=function(){if(___cxa_is_pointer_type(this.get_type()))return GROWABLE_HEAP_U32()[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var ___resumeException=e=>{throw exceptionLast||(exceptionLast=e),exceptionLast},findMatchingCatch=e=>{var t=exceptionLast;if(!t)return setTempRet0(0),0;var r=new ExceptionInfo(t);r.set_adjusted_ptr(t);var n=r.get_type();if(!n)return setTempRet0(0),t;for(var a in e){var o=e[a];if(0===o||o===n)break;var i=r.ptr+16;if(___cxa_can_catch(o,n,i))return setTempRet0(o),t}return setTempRet0(n),t},___cxa_find_matching_catch_2=()=>findMatchingCatch([]),___cxa_find_matching_catch_3=e=>findMatchingCatch([e]),___cxa_rethrow=()=>{var e=exceptionCaught.pop();e||abort("no exception to throw");var t=e.excPtr;throw e.get_rethrown()||(exceptionCaught.push(e),e.set_rethrown(!0),e.set_caught(!1),uncaughtExceptionCount++),exceptionLast=t},___cxa_rethrow_primary_exception=e=>{if(e){var t=new ExceptionInfo(e);exceptionCaught.push(t),t.set_rethrown(!0),___cxa_rethrow()}},___cxa_throw=(e,t,r)=>{throw new ExceptionInfo(e).init(t,r),uncaughtExceptionCount++,exceptionLast=e},___cxa_uncaught_exceptions=()=>uncaughtExceptionCount,___emscripten_init_main_thread_js=e=>{__emscripten_thread_init(e,!ENVIRONMENT_IS_WORKER,1,!ENVIRONMENT_IS_WEB,20971520,!1),PThread.threadInitTLS()},___emscripten_thread_cleanup=e=>{ENVIRONMENT_IS_PTHREAD?postMessage({cmd:"cleanupThread",thread:e}):cleanupThread(e)};function pthreadCreateProxied(e,t,r,n){return ENVIRONMENT_IS_PTHREAD?proxyToMainThread(2,1,e,t,r,n):___pthread_create_js(e,t,r,n)}var ___pthread_create_js=(e,t,r,n)=>{if("undefined"==typeof SharedArrayBuffer)return err("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];if(ENVIRONMENT_IS_PTHREAD&&0===a.length)return pthreadCreateProxied(e,t,r,n);var o={startRoutine:r,pthread_ptr:e,arg:n,transferList:a};return ENVIRONMENT_IS_PTHREAD?(o.cmd="spawnThread",postMessage(o,a),0):spawnThread(o)};function ___syscall__newselect(e,t,r,n,a){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(3,1,e,t,r,n,a);try{for(var o=0,i=t?GROWABLE_HEAP_I32()[t>>2]:0,s=t?GROWABLE_HEAP_I32()[t+4>>2]:0,_=r?GROWABLE_HEAP_I32()[r>>2]:0,l=r?GROWABLE_HEAP_I32()[r+4>>2]:0,c=n?GROWABLE_HEAP_I32()[n>>2]:0,u=n?GROWABLE_HEAP_I32()[n+4>>2]:0,d=0,m=0,f=0,E=0,p=0,h=0,S=(t?GROWABLE_HEAP_I32()[t>>2]:0)|(r?GROWABLE_HEAP_I32()[r>>2]:0)|(n?GROWABLE_HEAP_I32()[n>>2]:0),g=(t?GROWABLE_HEAP_I32()[t+4>>2]:0)|(r?GROWABLE_HEAP_I32()[r+4>>2]:0)|(n?GROWABLE_HEAP_I32()[n+4>>2]:0),v=function(e,t,r,n){return e<32?t&n:r&n},y=0;y>2]:0)+(t?GROWABLE_HEAP_I32()[a+8>>2]:0)/1e6);A=w.stream_ops.poll(w,T)}1&A&&v(y,i,s,F)&&(y<32?d|=F:m|=F,o++),4&A&&v(y,_,l,F)&&(y<32?f|=F:E|=F,o++),2&A&&v(y,c,u,F)&&(y<32?p|=F:h|=F,o++)}}return t&&(GROWABLE_HEAP_I32()[t>>2]=d,GROWABLE_HEAP_I32()[t+4>>2]=m),r&&(GROWABLE_HEAP_I32()[r>>2]=f,GROWABLE_HEAP_I32()[r+4>>2]=E),n&&(GROWABLE_HEAP_I32()[n>>2]=p,GROWABLE_HEAP_I32()[n+4>>2]=h),o}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var SOCKFS={mount:e=>(Module.websocket=Module.websocket&&"object"==typeof Module.websocket?Module.websocket:{},Module.websocket._callbacks={},Module.websocket.on=function(e,t){return"function"==typeof t&&(this._callbacks[e]=t),this},Module.websocket.emit=function(e,t){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,t)},FS.createNode(null,"/",16895,0)),createSocket(e,t,r){if(1==(t&=-526337)&&r&&6!=r)throw new FS.ErrnoError(66);var n={family:e,type:t,protocol:r,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},a=SOCKFS.nextname(),o=FS.createNode(SOCKFS.root,a,49152,0);o.sock=n;var i=FS.createStream({path:a,node:o,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return n.stream=i,n},getSocket(e){var t=FS.getStream(e);return t&&FS.isSocket(t.node.mode)?t.node.sock:null},stream_ops:{poll(e){var t=e.node.sock;return t.sock_ops.poll(t)},ioctl(e,t,r){var n=e.node.sock;return n.sock_ops.ioctl(n,t,r)},read(e,t,r,n,a){var o=e.node.sock,i=o.sock_ops.recvmsg(o,n);return i?(t.set(i.buffer,r),i.buffer.length):0},write(e,t,r,n,a){var o=e.node.sock;return o.sock_ops.sendmsg(o,t,r,n)},close(e){var t=e.node.sock;t.sock_ops.close(t)}},nextname:()=>(SOCKFS.nextname.current||(SOCKFS.nextname.current=0),"socket["+SOCKFS.nextname.current+++"]"),websocket_sock_ops:{createPeer(e,t,r){var n;if("object"==typeof t&&(n=t,t=null,r=null),n)if(n._socket)t=n._socket.remoteAddress,r=n._socket.remotePort;else{var a=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!a)throw new Error("WebSocket URL must be in the format ws(s)://address:port");t=a[1],r=parseInt(a[2],10)}else try{var o=Module.websocket&&"object"==typeof Module.websocket,i="ws:#".replace("#","//");if(o&&"string"==typeof Module.websocket.url&&(i=Module.websocket.url),"ws://"===i||"wss://"===i){var s=t.split("/");i=i+s[0]+":"+r+"/"+s.slice(1).join("/")}var _="binary";o&&"string"==typeof Module.websocket.subprotocol&&(_=Module.websocket.subprotocol);var l=void 0;"null"!==_&&(l=_=_.replace(/^ +| +$/g,"").split(/ *, */)),o&&null===Module.websocket.subprotocol&&(_="null",l=void 0),(n=new WebSocket(i,l)).binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}var c={addr:t,port:r,socket:n,dgram_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,c),SOCKFS.websocket_sock_ops.handlePeerEvents(e,c),2===e.type&&void 0!==e.sport&&c.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),c},getPeer:(e,t,r)=>e.peers[t+":"+r],addPeer(e,t){e.peers[t.addr+":"+t.port]=t},removePeer(e,t){delete e.peers[t.addr+":"+t.port]},handlePeerEvents(e,t){var r=!0,n=function(){Module.websocket.emit("open",e.stream.fd);try{for(var r=t.dgram_send_queue.shift();r;)t.socket.send(r),r=t.dgram_send_queue.shift()}catch(e){t.socket.close()}};function a(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(assert(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var a=r;if(r=!1,a&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var o=n[8]<<8|n[9];return SOCKFS.websocket_sock_ops.removePeer(e,t),t.port=o,void SOCKFS.websocket_sock_ops.addPeer(e,t)}e.recv_queue.push({addr:t.addr,port:t.port,data:n}),Module.websocket.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(t.socket.on("open",n),t.socket.on("message",function(e,t){t&&a(new Uint8Array(e).buffer)}),t.socket.on("close",function(){Module.websocket.emit("close",e.stream.fd)}),t.socket.on("error",function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(t.socket.onopen=n,t.socket.onclose=function(){Module.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){a(e.data)},t.socket.onerror=function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(1===e.type&&e.server)return e.pending.length?65:0;var t=0,r=1===e.type?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!r||r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=65),(!r||r&&r.socket.readyState===r.socket.OPEN)&&(t|=4),(r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=16),t},ioctl(e,t,r){if(21531===t){var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),GROWABLE_HEAP_I32()[r>>2]=n,0}return 28},close(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var t=Object.keys(e.peers),r=0;r{var t=SOCKFS.getSocket(e);if(!t)throw new FS.ErrnoError(8);return t},setErrNo=e=>(GROWABLE_HEAP_I32()[___errno_location()>>2]=e,e),inetNtop4=e=>(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var t="",r=0,n=0,a=0,o=0,i=0,s=0,_=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],l=!0,c="";for(s=0;s<5;s++)if(0!==_[s]){l=!1;break}if(l){if(c=inetNtop4(_[6]|_[7]<<16),-1===_[5])return t="::ffff:",t+=c;if(0===_[5])return t="::","0.0.0.0"===c&&(c=""),"0.0.0.1"===c&&(c="1"),t+=c}for(r=0;r<8;r++)0===_[r]&&(r-a>1&&(i=0),a=r,i++),i>n&&(o=r-(n=i)+1);for(r=0;r<8;r++)n>1&&0===_[r]&&r>=o&&r{var r,n=GROWABLE_HEAP_I16()[e>>1],a=_ntohs(GROWABLE_HEAP_U16()[e+2>>1]);switch(n){case 2:if(16!==t)return{errno:28};r=GROWABLE_HEAP_I32()[e+4>>2],r=inetNtop4(r);break;case 10:if(28!==t)return{errno:28};r=[GROWABLE_HEAP_I32()[e+8>>2],GROWABLE_HEAP_I32()[e+12>>2],GROWABLE_HEAP_I32()[e+16>>2],GROWABLE_HEAP_I32()[e+20>>2]],r=inetNtop6(r);break;default:return{errno:5}}return{family:n,addr:r,port:a}},inetPton4=e=>{for(var t=e.split("."),r=0;r<4;r++){var n=Number(t[r]);if(isNaN(n))return null;t[r]=n}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var t,r,n,a,o=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jstoi_q(t[t.length-4])+256*jstoi_q(t[t.length-3]),t[t.length-3]=jstoi_q(t[t.length-2])+256*jstoi_q(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),n=0,a=0,r=0;rDNS.address_map.names[e]?DNS.address_map.names[e]:null},getSocketAddress=(e,t,r)=>{if(r&&0===e)return null;var n=readSockaddr(e,t);if(n.errno)throw new FS.ErrnoError(n.errno);return n.addr=DNS.lookup_addr(n.addr)||n.addr,n};function ___syscall_connect(e,t,r,n,a,o){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(4,1,e,t,r,n,a,o);try{var i=getSocketFromFD(e),s=getSocketAddress(t,r);return i.sock_ops.connect(i,s.addr,s.port),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_faccessat(e,t,r,n){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(5,1,e,t,r,n);try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),-8&r)return-28;var a=FS.lookupPath(t,{follow:!0}).node;if(!a)return-44;var o="";return 4&r&&(o+="r"),2&r&&(o+="w"),1&r&&(o+="x"),o&&FS.nodePermissions(a,o)?-2:0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fcntl64(e,t,r){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(6,1,e,t,r);SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 0:if((a=SYSCALLS.get())<0)return-28;for(;FS.streams[a];)a++;return FS.createStream(n,a).fd;case 1:case 2:case 6:case 7:return 0;case 3:return n.flags;case 4:var a=SYSCALLS.get();return n.flags|=a,0;case 5:a=SYSCALLS.getp();return GROWABLE_HEAP_I16()[a+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return setErrNo(28),-1}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fstat64(e,t){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(7,1,e,t);try{var r=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,r.path,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var stringToUTF8=(e,t,r)=>stringToUTF8Array(e,GROWABLE_HEAP_U8(),t,r);function ___syscall_getcwd(e,t){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(8,1,e,t);try{if(0===t)return-28;var r=FS.cwd(),n=lengthBytesUTF8(r)+1;return t>>0,(tempDouble=_,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[t+o>>2]=tempI64[0],GROWABLE_HEAP_I32()[t+o+4>>2]=tempI64[1],tempI64=[(s+1)*a>>>0,(tempDouble=(s+1)*a,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[t+o+8>>2]=tempI64[0],GROWABLE_HEAP_I32()[t+o+12>>2]=tempI64[1],GROWABLE_HEAP_I16()[t+o+16>>1]=280,GROWABLE_HEAP_I8()[t+o+18|0]=l,stringToUTF8(c,t+o+19,256),o+=a,s+=1}return FS.llseek(n,s*a,0),o}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_ioctl(e,t,r){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(10,1,e,t,r);SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return n.tty?0:-59;case 21505:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var a=n.tty.ops.ioctl_tcgets(n),o=SYSCALLS.getp();GROWABLE_HEAP_I32()[o>>2]=a.c_iflag||0,GROWABLE_HEAP_I32()[o+4>>2]=a.c_oflag||0,GROWABLE_HEAP_I32()[o+8>>2]=a.c_cflag||0,GROWABLE_HEAP_I32()[o+12>>2]=a.c_lflag||0;for(var i=0;i<32;i++)GROWABLE_HEAP_I8()[o+i+17|0]=a.c_cc[i]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){o=SYSCALLS.getp();var s=GROWABLE_HEAP_I32()[o>>2],_=GROWABLE_HEAP_I32()[o+4>>2],l=GROWABLE_HEAP_I32()[o+8>>2],c=GROWABLE_HEAP_I32()[o+12>>2],u=[];for(i=0;i<32;i++)u.push(GROWABLE_HEAP_I8()[o+i+17|0]);return n.tty.ops.ioctl_tcsets(n.tty,t,{c_iflag:s,c_oflag:_,c_cflag:l,c_lflag:c,c_cc:u})}return 0;case 21519:if(!n.tty)return-59;o=SYSCALLS.getp();return GROWABLE_HEAP_I32()[o>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:o=SYSCALLS.getp();return FS.ioctl(n,t,o);case 21523:if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var d=n.tty.ops.ioctl_tiocgwinsz(n.tty);o=SYSCALLS.getp();GROWABLE_HEAP_I16()[o>>1]=d[0],GROWABLE_HEAP_I16()[o+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_lstat64(e,t){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(11,1,e,t);try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.lstat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_mkdirat(e,t,r){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(12,1,e,t,r);try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),"/"===(t=PATH.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),FS.mkdir(t,r,0),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_newfstatat(e,t,r,n){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(13,1,e,t,r,n);try{t=SYSCALLS.getStr(t);var a=256&n,o=4096&n;return n&=-6401,t=SYSCALLS.calculateAt(e,t,o),SYSCALLS.doStat(a?FS.lstat:FS.stat,t,r)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_openat(e,t,r,n){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(14,1,e,t,r,n);SYSCALLS.varargs=n;try{t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t);var a=n?SYSCALLS.get():0;return FS.open(t,r,a).fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_readlinkat(e,t,r,n){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(15,1,e,t,r,n);try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),n<=0)return-28;var a=FS.readlink(t),o=Math.min(n,lengthBytesUTF8(a)),i=GROWABLE_HEAP_I8()[r+o];return stringToUTF8(a,r,n+1),GROWABLE_HEAP_I8()[r+o]=i,o}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_rmdir(e){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(16,1,e);try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_socket(e,t,r){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(17,1,e,t,r);try{return SOCKFS.createSocket(e,t,r).stream.fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_stat64(e,t){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(18,1,e,t);try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_unlinkat(e,t,r){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(19,1,e,t,r);try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),0===r?FS.unlink(t):512===r?FS.rmdir(t):abort("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var nowIsMonotonic=!0,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic,maybeExit=()=>{if(!keepRuntimeAlive())try{ENVIRONMENT_IS_PTHREAD?__emscripten_thread_exit(EXITSTATUS):_exit(EXITSTATUS)}catch(e){handleException(e)}},callUserCallback=e=>{if(!ABORT)try{e(),maybeExit()}catch(e){handleException(e)}},__emscripten_thread_mailbox_await=e=>{if("function"==typeof Atomics.waitAsync){Atomics.waitAsync(GROWABLE_HEAP_I32(),e>>2,e).value.then(checkMailbox);var t=e+128;Atomics.store(GROWABLE_HEAP_I32(),t>>2,1)}};Module.__emscripten_thread_mailbox_await=__emscripten_thread_mailbox_await;var checkMailbox=()=>{var e=_pthread_self();e&&(__emscripten_thread_mailbox_await(e),callUserCallback(()=>__emscripten_check_mailbox()))};Module.checkMailbox=checkMailbox;var __emscripten_notify_mailbox_postmessage=(e,t,r)=>{if(e==t)setTimeout(()=>checkMailbox());else if(ENVIRONMENT_IS_PTHREAD)postMessage({targetThread:e,cmd:"checkMailbox"});else{var n=PThread.pthreads[e];if(!n)return;n.postMessage({cmd:"checkMailbox"})}},withStackSave=e=>{var t=stackSave(),r=e();return stackRestore(t),r},proxyToMainThread=function(e,t){var r=arguments.length-2,n=arguments;return withStackSave(()=>{for(var a=r,o=stackAlloc(8*a),i=o>>3,s=0;s{proxiedJSCallArgs.length=r;for(var a=n>>3,o=0;o{},convertI32PairToI53Checked=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN;function __gmtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),a=new Date(1e3*n);GROWABLE_HEAP_I32()[r>>2]=a.getUTCSeconds(),GROWABLE_HEAP_I32()[r+4>>2]=a.getUTCMinutes(),GROWABLE_HEAP_I32()[r+8>>2]=a.getUTCHours(),GROWABLE_HEAP_I32()[r+12>>2]=a.getUTCDate(),GROWABLE_HEAP_I32()[r+16>>2]=a.getUTCMonth(),GROWABLE_HEAP_I32()[r+20>>2]=a.getUTCFullYear()-1900,GROWABLE_HEAP_I32()[r+24>>2]=a.getUTCDay();var o=Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0),i=(a.getTime()-o)/864e5|0;GROWABLE_HEAP_I32()[r+28>>2]=i}var isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>(isLeapYear(e.getFullYear())?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()]+e.getDate()-1;function __localtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),a=new Date(1e3*n);GROWABLE_HEAP_I32()[r>>2]=a.getSeconds(),GROWABLE_HEAP_I32()[r+4>>2]=a.getMinutes(),GROWABLE_HEAP_I32()[r+8>>2]=a.getHours(),GROWABLE_HEAP_I32()[r+12>>2]=a.getDate(),GROWABLE_HEAP_I32()[r+16>>2]=a.getMonth(),GROWABLE_HEAP_I32()[r+20>>2]=a.getFullYear()-1900,GROWABLE_HEAP_I32()[r+24>>2]=a.getDay();var o=0|ydayFromDate(a);GROWABLE_HEAP_I32()[r+28>>2]=o,GROWABLE_HEAP_I32()[r+36>>2]=-60*a.getTimezoneOffset();var i=new Date(a.getFullYear(),0,1),s=new Date(a.getFullYear(),6,1).getTimezoneOffset(),_=i.getTimezoneOffset(),l=0|(s!=_&&a.getTimezoneOffset()==Math.min(_,s));GROWABLE_HEAP_I32()[r+32>>2]=l}var __mktime_js=function(e){var t=(()=>{var t=new Date(GROWABLE_HEAP_I32()[e+20>>2]+1900,GROWABLE_HEAP_I32()[e+16>>2],GROWABLE_HEAP_I32()[e+12>>2],GROWABLE_HEAP_I32()[e+8>>2],GROWABLE_HEAP_I32()[e+4>>2],GROWABLE_HEAP_I32()[e>>2],0),r=GROWABLE_HEAP_I32()[e+32>>2],n=t.getTimezoneOffset(),a=new Date(t.getFullYear(),0,1),o=new Date(t.getFullYear(),6,1).getTimezoneOffset(),i=a.getTimezoneOffset(),s=Math.min(i,o);if(r<0)GROWABLE_HEAP_I32()[e+32>>2]=Number(o!=i&&s==n);else if(r>0!=(s==n)){var _=Math.max(i,o),l=r>0?s:_;t.setTime(t.getTime()+6e4*(l-n))}GROWABLE_HEAP_I32()[e+24>>2]=t.getDay();var c=0|ydayFromDate(t);return GROWABLE_HEAP_I32()[e+28>>2]=c,GROWABLE_HEAP_I32()[e>>2]=t.getSeconds(),GROWABLE_HEAP_I32()[e+4>>2]=t.getMinutes(),GROWABLE_HEAP_I32()[e+8>>2]=t.getHours(),GROWABLE_HEAP_I32()[e+12>>2]=t.getDate(),GROWABLE_HEAP_I32()[e+16>>2]=t.getMonth(),GROWABLE_HEAP_I32()[e+20>>2]=t.getYear(),t.getTime()/1e3})();return setTempRet0((tempDouble=t,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)),t>>>0};function __mmap_js(e,t,r,n,a,o,i,s){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(20,1,e,t,r,n,a,o,i,s);var _=convertI32PairToI53Checked(a,o);try{if(isNaN(_))return 61;var l=SYSCALLS.getStreamFromFD(n),c=FS.mmap(l,e,_,t,r),u=c.ptr;return GROWABLE_HEAP_I32()[i>>2]=c.allocated,GROWABLE_HEAP_U32()[s>>2]=u,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function __munmap_js(e,t,r,n,a,o,i){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(21,1,e,t,r,n,a,o,i);var s=convertI32PairToI53Checked(o,i);try{if(isNaN(s))return 61;var _=SYSCALLS.getStreamFromFD(a);2&r&&SYSCALLS.doMsync(e,_,t,n,s),FS.munmap(_)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var _emscripten_get_now,stringToNewUTF8=e=>{var t=lengthBytesUTF8(e)+1,r=_malloc(t);return r&&stringToUTF8(e,r,t),r},__tzset_js=(e,t,r)=>{var n=(new Date).getFullYear(),a=new Date(n,0,1),o=new Date(n,6,1),i=a.getTimezoneOffset(),s=o.getTimezoneOffset(),_=Math.max(i,s);function l(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}GROWABLE_HEAP_U32()[e>>2]=60*_,GROWABLE_HEAP_I32()[t>>2]=Number(i!=s);var c=l(a),u=l(o),d=stringToNewUTF8(c),m=stringToNewUTF8(u);s>2]=d,GROWABLE_HEAP_U32()[r+4>>2]=m):(GROWABLE_HEAP_U32()[r>>2]=m,GROWABLE_HEAP_U32()[r+4>>2]=d)},_abort=()=>{abort("")},readEmAsmArgsArray=[],readEmAsmArgs=(e,t)=>{var r;for(readEmAsmArgsArray.length=0;r=GROWABLE_HEAP_U8()[e++];){var n=105!=r;t+=(n&=112!=r)&&t%8?4:0,readEmAsmArgsArray.push(112==r?GROWABLE_HEAP_U32()[t>>2]:105==r?GROWABLE_HEAP_I32()[t>>2]:GROWABLE_HEAP_F64()[t>>3]),t+=n?8:4}return readEmAsmArgsArray},runEmAsmFunction=(e,t,r)=>{var n=readEmAsmArgs(t,r);return ASM_CONSTS[e].apply(null,n)},_emscripten_asm_const_int=(e,t,r)=>runEmAsmFunction(e,t,r),warnOnce=e=>{warnOnce.shown||(warnOnce.shown={}),warnOnce.shown[e]||(warnOnce.shown[e]=1,err(e))},_emscripten_check_blocking_allowed=()=>{},_emscripten_date_now=()=>Date.now(),_emscripten_errn=(e,t)=>err(UTF8ToString(e,t)),runtimeKeepalivePush=()=>{runtimeKeepaliveCounter+=1},_emscripten_exit_with_live_runtime=()=>{throw runtimeKeepalivePush(),"unwind"},getHeapMax=()=>2147483648,_emscripten_get_heap_max=()=>getHeapMax();_emscripten_get_now=()=>performance.timeOrigin+performance.now();var reallyNegative=e=>e<0||0===e&&1/e==-1/0,convertI32PairToI53=(e,t)=>(e>>>0)+4294967296*t,convertU32PairToI53=(e,t)=>(e>>>0)+4294967296*(t>>>0),reSign=(e,t)=>{if(e<=0)return e;var r=t<=32?Math.abs(1<=r&&(t<=32||e>r)&&(e=-2*r+e),e},unSign=(e,t)=>e>=0?e:t<=32?2*Math.abs(1<{for(var t=e;GROWABLE_HEAP_U8()[t];)++t;return t-e},formatString=(e,t)=>{var r=e,n=t;function a(e){var t;return n=function(e,t){return"double"!==t&&"i64"!==t||7&e&&(e+=4),e}(n,e),"double"===e?(t=GROWABLE_HEAP_F64()[n>>3],n+=8):"i64"==e?(t=[GROWABLE_HEAP_I32()[n>>2],GROWABLE_HEAP_I32()[n+4>>2]],n+=8):(e="i32",t=GROWABLE_HEAP_I32()[n>>2],n+=4),t}for(var o,i,s,_=[];;){var l=r;if(0===(o=GROWABLE_HEAP_I8()[r|0]))break;if(i=GROWABLE_HEAP_I8()[r+1|0],37==o){var c=!1,u=!1,d=!1,m=!1,f=!1;e:for(;;){switch(i){case 43:c=!0;break;case 45:u=!0;break;case 35:d=!0;break;case 48:if(m)break e;m=!0;break;case 32:f=!0;break;default:break e}r++,i=GROWABLE_HEAP_I8()[r+1|0]}var E=0;if(42==i)E=a("i32"),r++,i=GROWABLE_HEAP_I8()[r+1|0];else for(;i>=48&&i<=57;)E=10*E+(i-48),r++,i=GROWABLE_HEAP_I8()[r+1|0];var p,h=!1,S=-1;if(46==i){if(S=0,h=!0,r++,42==(i=GROWABLE_HEAP_I8()[r+1|0]))S=a("i32"),r++;else for(;;){var g=GROWABLE_HEAP_I8()[r+1|0];if(g<48||g>57)break;S=10*S+(g-48),r++}i=GROWABLE_HEAP_I8()[r+1|0]}switch(S<0&&(S=6,h=!1),String.fromCharCode(i)){case"h":104==GROWABLE_HEAP_I8()[r+2|0]?(r++,p=1):p=2;break;case"l":108==GROWABLE_HEAP_I8()[r+2|0]?(r++,p=8):p=4;break;case"L":case"q":case"j":p=8;break;case"z":case"t":case"I":p=4;break;default:p=null}switch(p&&r++,i=GROWABLE_HEAP_I8()[r+1|0],String.fromCharCode(i)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":var v=100==i||105==i;if(s=a("i"+8*(p=p||4)),8==p&&(s=117==i?convertU32PairToI53(s[0],s[1]):convertI32PairToI53(s[0],s[1])),p<=4){var y=Math.pow(256,p)-1;s=(v?reSign:unSign)(s&y,8*p)}var F=Math.abs(s),w="";if(100==i||105==i)R=reSign(s,8*p).toString(10);else if(117==i)R=unSign(s,8*p).toString(10),s=Math.abs(s);else if(111==i)R=(d?"0":"")+F.toString(8);else if(120==i||88==i){if(w=d&&0!=s?"0x":"",s<0){s=-s,R=(F-1).toString(16);for(var A=[],T=0;T=0&&(c?w="+"+w:f&&(w=" "+w)),"-"==R.charAt(0)&&(w="-"+w,R=R.substr(1));w.length+R.lengthk&&k>=-4?(i=(103==i?"f":"F").charCodeAt(0),S-=k+1):(i=(103==i?"e":"E").charCodeAt(0),S--),D=Math.min(S,20)}101==i||69==i?(R=s.toExponential(D),/[eE][-+]\d$/.test(R)&&(R=R.slice(0,-1)+"0"+R.slice(-1))):102!=i&&70!=i||(R=s.toFixed(D),0===s&&reallyNegative(s)&&(R="-"+R));var P=R.split("e");if(b&&!d)for(;P[0].length>1&&P[0].includes(".")&&("0"==P[0].slice(-1)||"."==P[0].slice(-1));)P[0]=P[0].slice(0,-1);else for(d&&-1==R.indexOf(".")&&(P[0]+=".");S>D++;)P[0]+="0";R=P[0]+(P.length>1?"e"+P[1]:""),69==i&&(R=R.toUpperCase()),s>=0&&(c?R="+"+R:f&&(R=" "+R))}else R=(s<0?"-":"")+"inf",m=!1;for(;R.length0;)_.push(32);u||_.push(a("i8"));break;case"n":var I=a("i32*");GROWABLE_HEAP_I32()[I>>2]=_.length;break;case"%":_.push(o);break;default:for(T=l;T=4)){t+=c+"\n";continue}u=E[1],d=E[2],m=E[3],f=0|E[4]}var p=!1;if(8&e){var h=emscripten_source_map.originalPositionFor({line:m,column:f});(p=h&&h.source)&&(64&e&&(h.source=h.source.substring(h.source.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=` at ${u} (${h.source}:${h.line}:${h.column})\n`)}(16&e||!p)&&(64&e&&(d=d.substring(d.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=(p?` = ${u}`:` at ${u}`)+` (${d}:${m}:${f})\n`)}return t=t.replace(/\s+$/,"")}var emscriptenLog=(e,t)=>{24&e&&(t=t.replace(/\s+$/,""),t+=(t.length>0?"\n":"")+getCallstack(e)),1&e?4&e||2&e?err(t):out(t):6&e?err(t):out(t)},_emscripten_log=(e,t,r)=>{var n=formatString(t,r),a=UTF8ArrayToString(n,0);emscriptenLog(e,a)},_emscripten_num_logical_cores=()=>navigator.hardwareConcurrency,growMemory=e=>{var t=(e-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch(e){}},_emscripten_resize_heap=e=>{var t=GROWABLE_HEAP_U8().length;if((e>>>=0)<=t)return!1;var r=getHeapMax();if(e>r)return!1;for(var n=(e,t)=>e+(t-e%t)%t,a=1;a<=4;a*=2){var o=t*(1+.2/a);o=Math.min(o,e+100663296);var i=Math.min(r,n(Math.max(e,o),65536));if(growMemory(i))return!0}return!1},ENV={},getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(var t in ENV)void 0===ENV[t]?delete e[t]:e[t]=ENV[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToAscii=(e,t)=>{for(var r=0;r{var o=t+r;GROWABLE_HEAP_U32()[e+4*a>>2]=o,stringToAscii(n,o),r+=n.length+1}),0},_environ_sizes_get=function(e,t){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(23,1,e,t);var r=getEnvStrings();GROWABLE_HEAP_U32()[e>>2]=r.length;var n=0;return r.forEach(e=>n+=e.length+1),GROWABLE_HEAP_U32()[t>>2]=n,0};function _fd_close(e){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(24,1,e);try{var t=SYSCALLS.getStreamFromFD(e);return FS.close(t),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doReadv=(e,t,r,n)=>{for(var a=0,o=0;o>2],s=GROWABLE_HEAP_U32()[t+4>>2];t+=8;var _=FS.read(e,GROWABLE_HEAP_I8(),i,s,n);if(_<0)return-1;if(a+=_,_>2]=o,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}function _fd_seek(e,t,r,n,a){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(26,1,e,t,r,n,a);var o=convertI32PairToI53Checked(t,r);try{if(isNaN(o))return 61;var i=SYSCALLS.getStreamFromFD(e);return FS.llseek(i,o,n),tempI64=[i.position>>>0,(tempDouble=i.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],GROWABLE_HEAP_I32()[a>>2]=tempI64[0],GROWABLE_HEAP_I32()[a+4>>2]=tempI64[1],i.getdents&&0===o&&0===n&&(i.getdents=null),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doWritev=(e,t,r,n)=>{for(var a=0,o=0;o>2],s=GROWABLE_HEAP_U32()[t+4>>2];t+=8;var _=FS.write(e,GROWABLE_HEAP_I8(),i,s,n);if(_<0)return-1;a+=_,void 0!==n&&(n+=_)}return a};function _fd_write(e,t,r,n){if(ENVIRONMENT_IS_PTHREAD)return proxyToMainThread(27,1,e,t,r,n);try{var a=SYSCALLS.getStreamFromFD(e),o=doWritev(a,t,r);return GROWABLE_HEAP_U32()[n>>2]=o,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var functionsInTableMap,arraySum=(e,t)=>{for(var r=0,n=0;n<=t;r+=e[n++]);return r},MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31],MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31],addDays=(e,t)=>{for(var r=new Date(e.getTime());t>0;){var n=isLeapYear(r.getFullYear()),a=r.getMonth(),o=(n?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[a];if(!(t>o-r.getDate()))return r.setDate(r.getDate()+t),r;t-=o-r.getDate()+1,r.setDate(1),a<11?r.setMonth(a+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r},writeArrayToMemory=(e,t)=>{GROWABLE_HEAP_I8().set(e,t)},_strftime=(e,t,r,n)=>{var a=GROWABLE_HEAP_U32()[n+40>>2],o={tm_sec:GROWABLE_HEAP_I32()[n>>2],tm_min:GROWABLE_HEAP_I32()[n+4>>2],tm_hour:GROWABLE_HEAP_I32()[n+8>>2],tm_mday:GROWABLE_HEAP_I32()[n+12>>2],tm_mon:GROWABLE_HEAP_I32()[n+16>>2],tm_year:GROWABLE_HEAP_I32()[n+20>>2],tm_wday:GROWABLE_HEAP_I32()[n+24>>2],tm_yday:GROWABLE_HEAP_I32()[n+28>>2],tm_isdst:GROWABLE_HEAP_I32()[n+32>>2],tm_gmtoff:GROWABLE_HEAP_I32()[n+36>>2],tm_zone:a?UTF8ToString(a):""},i=UTF8ToString(r),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var _ in s)i=i.replace(new RegExp(_,"g"),s[_]);var l=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["January","February","March","April","May","June","July","August","September","October","November","December"];function u(e,t,r){for(var n="number"==typeof e?e.toString():e||"";n.length0?1:0}var n;return 0===(n=r(e.getFullYear()-t.getFullYear()))&&0===(n=r(e.getMonth()-t.getMonth()))&&(n=r(e.getDate()-t.getDate())),n}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function E(e){var t=addDays(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),n=new Date(t.getFullYear()+1,0,4),a=f(r),o=f(n);return m(a,t)<=0?m(o,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var p={"%a":e=>l[e.tm_wday].substring(0,3),"%A":e=>l[e.tm_wday],"%b":e=>c[e.tm_mon].substring(0,3),"%B":e=>c[e.tm_mon],"%C":e=>d((e.tm_year+1900)/100|0,2),"%d":e=>d(e.tm_mday,2),"%e":e=>u(e.tm_mday,2," "),"%g":e=>E(e).toString().substring(2),"%G":e=>E(e),"%H":e=>d(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":e=>d(e.tm_mday+arraySum(isLeapYear(e.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,e.tm_mon-1),3),"%m":e=>d(e.tm_mon+1,2),"%M":e=>d(e.tm_min,2),"%n":()=>"\n","%p":e=>e.tm_hour>=0&&e.tm_hour<12?"AM":"PM","%S":e=>d(e.tm_sec,2),"%t":()=>"\t","%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&isLeapYear(e.tm_year)||(t=1)}}else{t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(4==n||5==n&&isLeapYear(e.tm_year%400-1))&&t++}return d(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>"%"};for(var _ in i=i.replace(/%%/g,"\0\0"),p)i.includes(_)&&(i=i.replace(new RegExp(_,"g"),p[_](o)));var h=intArrayFromString(i=i.replace(/\0\0/g,"%"),!1);return h.length>t?0:(writeArrayToMemory(h,e),h.length-1)},_strftime_l=(e,t,r,n,a)=>_strftime(e,t,r,n),uleb128Encode=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var t={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"},r={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},n=1;n{var r=e.slice(0,1),n=e.slice(1),a={i:127,p:127,j:126,f:125,d:124};t.push(96),uleb128Encode(n.length,t);for(var o=0;o{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function(sigToWasmTypes(t),e);var r=[1];generateFuncType(t,r);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(r.length,n),n.push.apply(n,r),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var a=new WebAssembly.Module(new Uint8Array(n));return new WebAssembly.Instance(a,{e:{f:e}}).exports.f},updateTableMap=(e,t)=>{if(functionsInTableMap)for(var r=e;r(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1},setWasmTableEntry=(e,t)=>wasmTable.set(e,t),addFunction=(e,t)=>{var r=getFunctionAddress(e);if(r)return r;var n=getEmptyTableSlot();try{setWasmTableEntry(n,e)}catch(r){if(!(r instanceof TypeError))throw r;var a=convertJsFunctionToWasm(e,t);setWasmTableEntry(n,a)}return functionsInTableMap.set(e,n),n},stringToUTF8OnStack=e=>{var t=lengthBytesUTF8(e)+1,r=stackAlloc(t);return stringToUTF8(e,r,t),r};PThread.init();var FSNode=function(e,t,r,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=FS.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n},readMode=365,writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(e){e?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(e){e?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}}),FS.FSNode=FSNode,FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit();var calledRun,proxiedFunctionTable=[_proc_exit,exitOnMainThread,pthreadCreateProxied,___syscall__newselect,___syscall_connect,___syscall_faccessat,___syscall_fcntl64,___syscall_fstat64,___syscall_getcwd,___syscall_getdents64,___syscall_ioctl,___syscall_lstat64,___syscall_mkdirat,___syscall_newfstatat,___syscall_openat,___syscall_readlinkat,___syscall_rmdir,___syscall_socket,___syscall_stat64,___syscall_unlinkat,__mmap_js,__munmap_js,_environ_get,_environ_sizes_get,_fd_close,_fd_read,_fd_seek,_fd_write],wasmImports={CreateDirectoryFetcher:_CreateDirectoryFetcher,DDN_ConvertElement:_DDN_ConvertElement,DDN_CreateDDNResult:_DDN_CreateDDNResult,DDN_CreateDDNResultItem:_DDN_CreateDDNResultItem,DDN_CreateIntermediateResultUnits:_DDN_CreateIntermediateResultUnits,DDN_CreateParameters:_DDN_CreateParameters,DDN_CreateTargetRoiDefConditionFilter:_DDN_CreateTargetRoiDefConditionFilter,DDN_CreateTaskAlgEntity:_DDN_CreateTaskAlgEntity,DDN_HasSection:_DDN_HasSection,DDN_ReadTaskSetting:_DDN_ReadTaskSetting,DLR_ConvertElement:_DLR_ConvertElement,DLR_CreateBufferedCharacterItemSet:_DLR_CreateBufferedCharacterItemSet,DLR_CreateIntermediateResultUnits:_DLR_CreateIntermediateResultUnits,DLR_CreateParameters:_DLR_CreateParameters,DLR_CreateRecognizedTextLinesResult:_DLR_CreateRecognizedTextLinesResult,DLR_CreateTargetRoiDefConditionFilter:_DLR_CreateTargetRoiDefConditionFilter,DLR_CreateTaskAlgEntity:_DLR_CreateTaskAlgEntity,DLR_CreateTextLineResultItem:_DLR_CreateTextLineResultItem,DLR_ReadTaskSetting:_DLR_ReadTaskSetting,DMImage_GetDIB:_DMImage_GetDIB,DMImage_GetOrientation:_DMImage_GetOrientation,DeleteDirectoryFetcher:_DeleteDirectoryFetcher,_ZN19LabelRecognizerWasm10getVersionEv:__ZN19LabelRecognizerWasm10getVersionEv,_ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv:__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv,_ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv:__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv,_ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi:__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi,_ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb:__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb,_ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb:__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb,_ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb:__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb,_ZN19LabelRecognizerWasm12DlrWasmClassC1Ev:__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev,_ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE:__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE,_ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE:__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE,_ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE:__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE,_ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE:__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE,_ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE:__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE,_ZN22DocumentNormalizerWasm10getVersionEv:__ZN22DocumentNormalizerWasm10getVersionEv,_ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv:__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv,_ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi:__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi,_ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii:__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii,_ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE,_ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev:__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev,_ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE:__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE,_ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE:__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE,_ZN9dynamsoft7utility14CUtilityModule10GetVersionEv:__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv,__assert_fail:___assert_fail,__cxa_begin_catch:___cxa_begin_catch,__cxa_end_catch:___cxa_end_catch,__cxa_find_matching_catch_2:___cxa_find_matching_catch_2,__cxa_find_matching_catch_3:___cxa_find_matching_catch_3,__cxa_rethrow:___cxa_rethrow,__cxa_rethrow_primary_exception:___cxa_rethrow_primary_exception,__cxa_throw:___cxa_throw,__cxa_uncaught_exceptions:___cxa_uncaught_exceptions,__emscripten_init_main_thread_js:___emscripten_init_main_thread_js,__emscripten_thread_cleanup:___emscripten_thread_cleanup,__pthread_create_js:___pthread_create_js,__resumeException:___resumeException,__syscall__newselect:___syscall__newselect,__syscall_connect:___syscall_connect,__syscall_faccessat:___syscall_faccessat,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_readlinkat:___syscall_readlinkat,__syscall_rmdir:___syscall_rmdir,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_unlinkat:___syscall_unlinkat,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_emscripten_notify_mailbox_postmessage:__emscripten_notify_mailbox_postmessage,_emscripten_receive_on_main_thread_js:__emscripten_receive_on_main_thread_js,_emscripten_thread_mailbox_await:__emscripten_thread_mailbox_await,_emscripten_thread_set_strongref:__emscripten_thread_set_strongref,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_mktime_js:__mktime_js,_mmap_js:__mmap_js,_munmap_js:__munmap_js,_tzset_js:__tzset_js,abort:_abort,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_check_blocking_allowed:_emscripten_check_blocking_allowed,emscripten_date_now:_emscripten_date_now,emscripten_errn:_emscripten_errn,emscripten_exit_with_live_runtime:_emscripten_exit_with_live_runtime,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_log:_emscripten_log,emscripten_num_logical_cores:_emscripten_num_logical_cores,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,exit:_exit,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,invoke_diii:invoke_diii,invoke_fiii:invoke_fiii,invoke_i:invoke_i,invoke_ii:invoke_ii,invoke_iii:invoke_iii,invoke_iiii:invoke_iiii,invoke_iiiii:invoke_iiiii,invoke_iiiiid:invoke_iiiiid,invoke_iiiiii:invoke_iiiiii,invoke_iiiiiii:invoke_iiiiiii,invoke_iiiiiiii:invoke_iiiiiiii,invoke_iiiiiiiiiiii:invoke_iiiiiiiiiiii,invoke_iiiiij:invoke_iiiiij,invoke_j:invoke_j,invoke_ji:invoke_ji,invoke_jii:invoke_jii,invoke_jiiii:invoke_jiiii,invoke_v:invoke_v,invoke_vi:invoke_vi,invoke_vii:invoke_vii,invoke_viid:invoke_viid,invoke_viii:invoke_viii,invoke_viiii:invoke_viiii,invoke_viiiiiii:invoke_viiiiiii,invoke_viiiiiiiiii:invoke_viiiiiiiiii,invoke_viiiiiiiiiiiiiii:invoke_viiiiiiiiiiiiiii,memory:wasmMemory,strftime:_strftime,strftime_l:_strftime_l},wasmExports=createWasm();function invoke_iiii(e,t,r,n){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(e,t){var r=stackSave();try{return getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(e,t,r){var n=stackSave();try{return getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(e,t,r){var n=stackSave();try{getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(e,t){var r=stackSave();try{getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(e){var t=stackSave();try{getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(e,t,r,n,a,o,i){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,a,o,i)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(e,t,r,n,a){var o=stackSave();try{getWasmTableEntry(e)(t,r,n,a)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(e,t,r,n,a,o){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,a,o)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiid(e,t,r,n,a,o){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,a,o)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(e,t,r,n){var a=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiii(e,t,r,n,a,o,i,s){var _=stackSave();try{return getWasmTableEntry(e)(t,r,n,a,o,i,s)}catch(e){if(stackRestore(_),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(e,t,r,n,a){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n,a)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(e,t,r,n){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_diii(e,t,r,n){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(e){var t=stackSave();try{return getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(e,t,r,n,a,o,i,s){var _=stackSave();try{getWasmTableEntry(e)(t,r,n,a,o,i,s)}catch(e){if(stackRestore(_),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(e,t,r,n,a,o,i,s,_,l,c,u){var d=stackSave();try{return getWasmTableEntry(e)(t,r,n,a,o,i,s,_,l,c,u)}catch(e){if(stackRestore(d),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(e,t,r,n,a,o,i,s,_,l,c){var u=stackSave();try{getWasmTableEntry(e)(t,r,n,a,o,i,s,_,l,c)}catch(e){if(stackRestore(u),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(e,t,r,n,a,o,i,s,_,l,c,u,d,m,f,E){var p=stackSave();try{getWasmTableEntry(e)(t,r,n,a,o,i,s,_,l,c,u,d,m,f,E)}catch(e){if(stackRestore(p),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(e,t,r,n){var a=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_j(e){var t=stackSave();try{return dynCall_j(e)}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(e,t){var r=stackSave();try{return dynCall_ji(e,t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(e,t,r){var n=stackSave();try{return dynCall_jii(e,t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiij(e,t,r,n,a,o,i){var s=stackSave();try{return dynCall_iiiiij(e,t,r,n,a,o,i)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(e,t,r,n,a){var o=stackSave();try{return dynCall_jiiii(e,t,r,n,a)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function run(){if(!(runDependencies>0)){if(ENVIRONMENT_IS_PTHREAD)return initRuntime(),void startWorker(Module);preRun(),runDependencies>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e())}function e(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT||(initRuntime(),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)]()[UTF8ToString(r)]()),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack((new(self[UTF8ToString(e)]))[UTF8ToString(t)](UTF8ToString(r))),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>{self[UTF8ToString(e)](null,UTF8ToString(t).trim(),UTF8ToString(r),n)},"viiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)][UTF8ToString(r)](UTF8ToString(n))?"":self[UTF8ToString(e)][UTF8ToString(t)]),"iiiii")),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun()))}}if(Module.keepRuntimeAlive=keepRuntimeAlive,Module.wasmMemory=wasmMemory,Module.addFunction=addFunction,Module.stringToUTF8OnStack=stringToUTF8OnStack,Module.ExitStatus=ExitStatus,dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)},Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();run(); \ No newline at end of file diff --git a/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.wasm b/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.wasm new file mode 100644 index 0000000..a8775f1 Binary files /dev/null and b/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.wasm differ diff --git a/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.worker.js b/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.worker.js new file mode 100644 index 0000000..c423667 --- /dev/null +++ b/dist/dynamsoft-barcode-reader-bundle-ml-simd-pthread.worker.js @@ -0,0 +1,6 @@ +/** + * @license + * Copyright 2015 The Emscripten Authors + * SPDX-License-Identifier: MIT + */ +"use strict";var Module={},initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;function handleMessage(e){try{if("load"===e.data.cmd){let t=[];self.onmessage=e=>t.push(e),self.startWorker=e=>{postMessage({cmd:"loaded"});for(let e of t)handleMessage(e);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const a of e.data.handlers)Module[a]=(...e)=>{postMessage({cmd:"callHandler",handler:a,args:e})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof e.data.urlOrBlob)importScripts(e.data.urlOrBlob);else{var a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}}else if("run"===e.data.cmd){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(e){if("unwind"!=e)throw e}}else"cancel"===e.data.cmd?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):"setimmediate"===e.data.target||("checkMailbox"===e.data.cmd?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(e){throw Module.__emscripten_thread_crashed&&Module.__emscripten_thread_crashed(),e}}self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var t=Module.wasmModule;return Module.wasmModule=null,a(new WebAssembly.Instance(t,e))},self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=handleMessage; \ No newline at end of file diff --git a/dist/dynamsoft-barcode-reader-bundle-ml-simd.js b/dist/dynamsoft-barcode-reader-bundle-ml-simd.js index e1fd8b8..e54bcf0 100644 --- a/dist/dynamsoft-barcode-reader-bundle-ml-simd.js +++ b/dist/dynamsoft-barcode-reader-bundle-ml-simd.js @@ -1 +1 @@ -var read_,readAsync,readBinary,Module=void 0!==Module?Module:{},moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(e,t)=>{throw t},ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!0,ENVIRONMENT_IS_NODE=!1,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:"undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=0!==scriptDirectory.indexOf("blob:")?scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1):"",read_=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),readAsync=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var wasmBinary,out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit),Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,noExitRuntime=Module.noExitRuntime||!0;"object"!=typeof WebAssembly&&abort("no native wasm support detected");var EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,ABORT=!1;function assert(e,t){e||abort(t)}function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e)}var __ATPRERUN__=[],__ATINIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,Module.noFSInit||FS.init.initialized||FS.init(),FS.ignorePermissions=!1,TTY.init(),SOCKFS.root=FS.mount(SOCKFS,{},null),callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module.postRun)for("function"==typeof Module.postRun&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(e){return e}function addRunDependency(e){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}function removeRunDependency(e){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}function abort(e){throw Module.onAbort&&Module.onAbort(e),err(e="Aborted("+e+")"),ABORT=!0,EXITSTATUS=1,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}var wasmBinaryFile,tempDouble,tempI64,dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(e){return e.startsWith(dataURIPrefix)}function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(e){return wasmBinary||!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER||"function"!=typeof fetch?Promise.resolve().then(()=>getBinarySync(e)):fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()}).catch(()=>getBinarySync(e))}function instantiateArrayBuffer(e,t,r){return getBinaryPromise(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(r,e=>{err(`failed to asynchronously prepare wasm: ${e}`),abort(e)})}function instantiateAsync(e,t,r,n){return e||"function"!=typeof WebAssembly.instantiateStreaming||isDataURI(t)||"function"!=typeof fetch?instantiateArrayBuffer(t,r,n):fetch(t,{credentials:"same-origin"}).then(e=>WebAssembly.instantiateStreaming(e,r).then(n,function(e){return err(`wasm streaming compile failed: ${e}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(t,r,n)}))}function createWasm(){var e={env:wasmImports,wasi_snapshot_preview1:wasmImports};function t(e,t){return wasmExports=e.exports,wasmMemory=wasmExports.memory,updateMemoryViews(),wasmTable=wasmExports.__indirect_function_table,addOnInit(wasmExports.__wasm_call_ctors),exportWasmSymbols(wasmExports),removeRunDependency("wasm-instantiate"),wasmExports}if(addRunDependency("wasm-instantiate"),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return err(`Module.instantiateWasm callback failed with error: ${e}`),!1}return instantiateAsync(wasmBinary,wasmBinaryFile,e,function(e){t(e.instance)}),{}}isDataURI(wasmBinaryFile="dynamsoft-barcode-reader-bundle-ml-simd.wasm")||(wasmBinaryFile=locateFile(wasmBinaryFile));var ASM_CONSTS={831112:(e,t,r,n)=>{if(void 0===Module||!Module.MountedFiles)return 1;let o=UTF8ToString(e>>>0);o.startsWith("./")&&(o=o.substring(2));const a=Module.MountedFiles.get(o);if(!a)return 2;const s=t>>>0,i=r>>>0,l=n>>>0;if(s+i>a.byteLength)return 3;try{return HEAPU8.set(a.subarray(s,s+i),l),0}catch{return 4}}},callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},asmjsMangle=e=>("__main_argc_argv"==e&&(e="main"),0==e.indexOf("dynCall_")||["stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0"].includes(e)?e:"_"+e),exportWasmSymbols=e=>{for(var t in e){var r=asmjsMangle(t);this[r]=Module[r]=e[t]}};function _CreateDirectoryFetcher(){abort("missing function: CreateDirectoryFetcher")}function _DDN_ConvertElement(){abort("missing function: DDN_ConvertElement")}function _DDN_CreateDDNResult(){abort("missing function: DDN_CreateDDNResult")}function _DDN_CreateDDNResultItem(){abort("missing function: DDN_CreateDDNResultItem")}function _DDN_CreateIntermediateResultUnits(){abort("missing function: DDN_CreateIntermediateResultUnits")}function _DDN_CreateParameters(){abort("missing function: DDN_CreateParameters")}function _DDN_CreateTargetRoiDefConditionFilter(){abort("missing function: DDN_CreateTargetRoiDefConditionFilter")}function _DDN_CreateTaskAlgEntity(){abort("missing function: DDN_CreateTaskAlgEntity")}function _DDN_HasSection(){abort("missing function: DDN_HasSection")}function _DDN_ReadTaskSetting(){abort("missing function: DDN_ReadTaskSetting")}function _DLR_ConvertElement(){abort("missing function: DLR_ConvertElement")}function _DLR_CreateBufferedCharacterItemSet(){abort("missing function: DLR_CreateBufferedCharacterItemSet")}function _DLR_CreateIntermediateResultUnits(){abort("missing function: DLR_CreateIntermediateResultUnits")}function _DLR_CreateParameters(){abort("missing function: DLR_CreateParameters")}function _DLR_CreateRecognizedTextLinesResult(){abort("missing function: DLR_CreateRecognizedTextLinesResult")}function _DLR_CreateTargetRoiDefConditionFilter(){abort("missing function: DLR_CreateTargetRoiDefConditionFilter")}function _DLR_CreateTaskAlgEntity(){abort("missing function: DLR_CreateTaskAlgEntity")}function _DLR_CreateTextLineResultItem(){abort("missing function: DLR_CreateTextLineResultItem")}function _DLR_ReadTaskSetting(){abort("missing function: DLR_ReadTaskSetting")}function _DMImage_GetDIB(){abort("missing function: DMImage_GetDIB")}function _DMImage_GetOrientation(){abort("missing function: DMImage_GetOrientation")}function _DeleteDirectoryFetcher(){abort("missing function: DeleteDirectoryFetcher")}function __ZN19LabelRecognizerWasm10getVersionEv(){abort("missing function: _ZN19LabelRecognizerWasm10getVersionEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi")}function __ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb")}function __ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClassC1Ev(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev")}function __ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE(){abort("missing function: _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE")}function __ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE(){abort("missing function: _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE")}function __ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE")}function __ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE")}function __ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE(){abort("missing function: _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE")}function __ZN22DocumentNormalizerWasm10getVersionEv(){abort("missing function: _ZN22DocumentNormalizerWasm10getVersionEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii")}function __ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE")}function __ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev")}function __ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE")}function __ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE")}function __ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E(){abort("missing function: _ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E")}function __ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E(){abort("missing function: _ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E")}function __ZN9dynamsoft7utility14CUtilityModule10GetVersionEv(){abort("missing function: _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv")}_CreateDirectoryFetcher.stub=!0,_DDN_ConvertElement.stub=!0,_DDN_CreateDDNResult.stub=!0,_DDN_CreateDDNResultItem.stub=!0,_DDN_CreateIntermediateResultUnits.stub=!0,_DDN_CreateParameters.stub=!0,_DDN_CreateTargetRoiDefConditionFilter.stub=!0,_DDN_CreateTaskAlgEntity.stub=!0,_DDN_HasSection.stub=!0,_DDN_ReadTaskSetting.stub=!0,_DLR_ConvertElement.stub=!0,_DLR_CreateBufferedCharacterItemSet.stub=!0,_DLR_CreateIntermediateResultUnits.stub=!0,_DLR_CreateParameters.stub=!0,_DLR_CreateRecognizedTextLinesResult.stub=!0,_DLR_CreateTargetRoiDefConditionFilter.stub=!0,_DLR_CreateTaskAlgEntity.stub=!0,_DLR_CreateTextLineResultItem.stub=!0,_DLR_ReadTaskSetting.stub=!0,_DMImage_GetDIB.stub=!0,_DMImage_GetOrientation.stub=!0,_DeleteDirectoryFetcher.stub=!0,__ZN19LabelRecognizerWasm10getVersionEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev.stub=!0,__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE.stub=!0,__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE.stub=!0,__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE.stub=!0,__ZN22DocumentNormalizerWasm10getVersionEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev.stub=!0,__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE.stub=!0,__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE.stub=!0,__ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E.stub=!0,__ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E.stub=!0,__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv.stub=!0;var UTF8Decoder="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,UTF8ArrayToString=(e,t,r)=>{for(var n=t+r,o=t;e[o]&&!(o>=n);)++o;if(o-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&c)}}else a+=String.fromCharCode((31&s)<<6|i)}else a+=String.fromCharCode(s)}return a},UTF8ToString=(e,t)=>e?UTF8ArrayToString(HEAPU8,e,t):"",___assert_fail=(e,t,r,n)=>{abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[t?UTF8ToString(t):"unknown filename",r,n?UTF8ToString(n):"unknown function"])},exceptionCaught=[],uncaughtExceptionCount=0,___cxa_begin_catch=e=>{var t=new ExceptionInfo(e);return t.get_caught()||(t.set_caught(!0),uncaughtExceptionCount--),t.set_rethrown(!1),exceptionCaught.push(t),___cxa_increment_exception_refcount(t.excPtr),t.get_exception_ptr()},exceptionLast=0,___cxa_end_catch=()=>{_setThrew(0,0);var e=exceptionCaught.pop();___cxa_decrement_exception_refcount(e.excPtr),exceptionLast=0};function ExceptionInfo(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){HEAPU32[this.ptr+4>>2]=e},this.get_type=function(){return HEAPU32[this.ptr+4>>2]},this.set_destructor=function(e){HEAPU32[this.ptr+8>>2]=e},this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,HEAP8[this.ptr+12|0]=e},this.get_caught=function(){return 0!=HEAP8[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,HEAP8[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=HEAP8[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){HEAPU32[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]},this.get_exception_ptr=function(){if(___cxa_is_pointer_type(this.get_type()))return HEAPU32[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var ___resumeException=e=>{throw exceptionLast||(exceptionLast=e),exceptionLast},findMatchingCatch=e=>{var t=exceptionLast;if(!t)return setTempRet0(0),0;var r=new ExceptionInfo(t);r.set_adjusted_ptr(t);var n=r.get_type();if(!n)return setTempRet0(0),t;for(var o in e){var a=e[o];if(0===a||a===n)break;var s=r.ptr+16;if(___cxa_can_catch(a,n,s))return setTempRet0(a),t}return setTempRet0(n),t},___cxa_find_matching_catch_2=()=>findMatchingCatch([]),___cxa_find_matching_catch_3=e=>findMatchingCatch([e]),___cxa_rethrow=()=>{var e=exceptionCaught.pop();e||abort("no exception to throw");var t=e.excPtr;throw e.get_rethrown()||(exceptionCaught.push(e),e.set_rethrown(!0),e.set_caught(!1),uncaughtExceptionCount++),exceptionLast=t},___cxa_rethrow_primary_exception=e=>{if(e){var t=new ExceptionInfo(e);exceptionCaught.push(t),t.set_rethrown(!0),___cxa_rethrow()}},___cxa_throw=(e,t,r)=>{throw new ExceptionInfo(e).init(t,r),uncaughtExceptionCount++,exceptionLast=e},___cxa_uncaught_exceptions=()=>uncaughtExceptionCount,PATH={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=PATH.isAbs(e),r="/"===e.substr(-1);return(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=PATH.splitPath(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=PATH.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return PATH.normalize(e.join("/"))},join2:(e,t)=>PATH.normalize(e+"/"+t)},initRandomFill=()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:FS.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,t=PATH.isAbs(n)}return(t?"/":"")+(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=PATH_FS.resolve(e).substr(1),t=PATH_FS.resolve(t).substr(1);for(var n=r(e.split("/")),o=r(t.split("/")),a=Math.min(n.length,o.length),s=a,i=0;i{for(var t=0,r=0;r=55296&&n<=57343?(t+=4,++r):t+=3}return t},stringToUTF8Array=(e,t,r,n)=>{if(!(n>0))return 0;for(var o=r,a=r+n-1,s=0;s=55296&&i<=57343)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++s);if(i<=127){if(r>=a)break;t[r++]=i}else if(i<=2047){if(r+1>=a)break;t[r++]=192|i>>6,t[r++]=128|63&i}else if(i<=65535){if(r+2>=a)break;t[r++]=224|i>>12,t[r++]=128|i>>6&63,t[r++]=128|63&i}else{if(r+3>=a)break;t[r++]=240|i>>18,t[r++]=128|i>>12&63,t[r++]=128|i>>6&63,t[r++]=128|63&i}}return t[r]=0,r-o};function intArrayFromString(e,t,r){var n=r>0?r:lengthBytesUTF8(e)+1,o=new Array(n),a=stringToUTF8Array(e,o,0,o.length);return t&&(o.length=a),o}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,t){TTY.ttys[e]={input:[],output:[],ops:t},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var t=TTY.ttys[e.node.rdev];if(!t)throw new FS.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,r,n,o){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var a=0,s=0;sFS_stdin_getChar(),put_char(e,t){null===t||10===t?(out(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(out(UTF8ArrayToString(e.output,0)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,r)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(err(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output,0)),e.output=[])}}},zeroMemory=(e,t)=>(HEAPU8.fill(0,e,e+t),e),alignMemory=(e,t)=>Math.ceil(e/t)*t,mmapAlloc=e=>{e=alignMemory(e,65536);var t=_emscripten_builtin_memalign(65536,e);return t?zeroMemory(t,e):0},MEMFS={ops_table:null,mount:e=>MEMFS.createNode(null,"/",16895,0),createNode(e,t,r,n){if(FS.isBlkdev(r)||FS.isFIFO(r))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var o=FS.createNode(e,t,r,n);return FS.isDir(o.mode)?(o.node_ops=MEMFS.ops_table.dir.node,o.stream_ops=MEMFS.ops_table.dir.stream,o.contents={}):FS.isFile(o.mode)?(o.node_ops=MEMFS.ops_table.file.node,o.stream_ops=MEMFS.ops_table.file.stream,o.usedBytes=0,o.contents=null):FS.isLink(o.mode)?(o.node_ops=MEMFS.ops_table.link.node,o.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(o.mode)&&(o.node_ops=MEMFS.ops_table.chrdev.node,o.stream_ops=MEMFS.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var n=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=FS.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,FS.isDir(e.mode)?t.size=4096:FS.isFile(e.mode)?t.size=e.usedBytes:FS.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&MEMFS.resizeFileStorage(e,t.size)},lookup(e,t){throw FS.genericErrors[44]},mknod:(e,t,r,n)=>MEMFS.createNode(e,t,r,n),rename(e,t,r){if(FS.isDir(e.mode)){var n;try{n=FS.lookupNode(t,r)}catch(e){}if(n)for(var o in n.contents)throw new FS.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=FS.lookupNode(e,t);for(var n in r.contents)throw new FS.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var n=MEMFS.createNode(e,t,41471,0);return n.link=r,n},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-o,n);if(s>8&&a.subarray)t.set(a.subarray(o,o+s),r);else for(var i=0;i0||r+t(MEMFS.stream_ops.write(e,t,0,n,r,!1),0)}},asyncLoad=(e,t,r,n)=>{var o=n?"":getUniqueRunDependency(`al ${e}`);readAsync(e,r=>{assert(r,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(r)),o&&removeRunDependency(o)},t=>{if(!r)throw`Loading data file "${e}" failed.`;r()}),o&&addRunDependency(o)},FS_createDataFile=(e,t,r,n,o,a)=>FS.createDataFile(e,t,r,n,o,a),preloadPlugins=Module.preloadPlugins||[],FS_handledByPreloadPlugin=(e,t,r,n)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return preloadPlugins.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,r,n),o=!0)}),o},FS_createPreloadedFile=(e,t,r,n,o,a,s,i,l,c)=>{var u=t?PATH_FS.resolve(PATH.join2(e,t)):e,m=getUniqueRunDependency(`cp ${u}`);function d(r){function d(r){c&&c(),i||FS_createDataFile(e,t,r,n,o,l),a&&a(),removeRunDependency(m)}FS_handledByPreloadPlugin(r,u,d,()=>{s&&s(),removeRunDependency(m)})||d(r)}addRunDependency(m),"string"==typeof r?asyncLoad(r,e=>d(e),s):d(r)},FS_modeStringToFlags=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t},FS_getMode=(e,t)=>{var r=0;return e&&(r|=365),t&&(r|=146),r},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(!(e=PATH_FS.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new FS.ErrnoError(32);for(var r=e.split("/").filter(e=>!!e),n=FS.root,o="/",a=0;a40)throw new FS.ErrnoError(32)}}return{path:o,node:n}},getPath(e){for(var t;;){if(FS.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?`${r}/${t}`:r+t:r}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var r=0,n=0;n>>0)%FS.nameTable.length},hashAddNode(e){var t=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[t],FS.nameTable[t]=e},hashRemoveNode(e){var t=FS.hashName(e.parent.id,e.name);if(FS.nameTable[t]===e)FS.nameTable[t]=e.name_next;else for(var r=FS.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode(e,t){var r=FS.mayLookup(e);if(r)throw new FS.ErrnoError(r,e);for(var n=FS.hashName(e.id,t),o=FS.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return FS.lookup(e,t)},createNode(e,t,r,n){var o=new FS.FSNode(e,t,r,n);return FS.hashAddNode(o),o},destroyNode(e){FS.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>FS.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){var t=FS.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{FS.lookupNode(e,t);return 20}catch(e){}return FS.nodePermissions(e,"wx")},mayDelete(e,t,r){var n;try{n=FS.lookupNode(e,t)}catch(e){return e.errno}var o=FS.nodePermissions(e,"wx");if(o)return o;if(r){if(!FS.isDir(n.mode))return 54;if(FS.isRoot(n)||FS.getPath(n)===FS.cwd())return 10}else if(FS.isDir(n.mode))return 31;return 0},mayOpen:(e,t)=>e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&("r"!==FS.flagsToPermissionString(t)||512&t)?31:FS.nodePermissions(e,FS.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var t=FS.getStream(e);if(!t)throw new FS.ErrnoError(8);return t},getStream:e=>FS.streams[e],createStream:(e,t=-1)=>(FS.FSStream||(FS.FSStream=function(){this.shared={}},FS.FSStream.prototype={},Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new FS.FSStream,e),-1==t&&(t=FS.nextfd()),e.fd=t,FS.streams[t]=e,e),closeStream(e){FS.streams[e]=null},chrdev_stream_ops:{open(e){var t=FS.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){FS.devices[e]={stream_ops:t}},getDevice:e=>FS.devices[e],getMounts(e){for(var t=[],r=[e];r.length;){var n=r.pop();t.push(n),r.push.apply(r,n.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var r=FS.getMounts(FS.root.mount),n=0;function o(e){return FS.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=r.length&&o(null)}r.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,r){var n,o="/"===r,a=!r;if(o&&FS.root)throw new FS.ErrnoError(10);if(!o&&!a){var s=FS.lookupPath(r,{follow_mount:!1});if(r=s.path,n=s.node,FS.isMountpoint(n))throw new FS.ErrnoError(10);if(!FS.isDir(n.mode))throw new FS.ErrnoError(54)}var i={type:e,opts:t,mountpoint:r,mounts:[]},l=e.mount(i);return l.mount=i,i.root=l,o?FS.root=l:n&&(n.mounted=i,n.mount&&n.mount.mounts.push(i)),l},unmount(e){var t=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(t.node))throw new FS.ErrnoError(28);var r=t.node,n=r.mounted,o=FS.getMounts(n);Object.keys(FS.nameTable).forEach(e=>{for(var t=FS.nameTable[e];t;){var r=t.name_next;o.includes(t.mount)&&FS.destroyNode(t),t=r}}),r.mounted=null;var a=r.mount.mounts.indexOf(n);r.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,r){var n=FS.lookupPath(e,{parent:!0}).node,o=PATH.basename(e);if(!o||"."===o||".."===o)throw new FS.ErrnoError(28);var a=FS.mayCreate(n,o);if(a)throw new FS.ErrnoError(a);if(!n.node_ops.mknod)throw new FS.ErrnoError(63);return n.node_ops.mknod(n,o,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,FS.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,FS.mknod(e,t,0)),mkdirTree(e,t){for(var r=e.split("/"),n="",o=0;o(void 0===r&&(r=t,t=438),t|=8192,FS.mknod(e,t,r)),symlink(e,t){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var r=FS.lookupPath(t,{parent:!0}).node;if(!r)throw new FS.ErrnoError(44);var n=PATH.basename(t),o=FS.mayCreate(r,n);if(o)throw new FS.ErrnoError(o);if(!r.node_ops.symlink)throw new FS.ErrnoError(63);return r.node_ops.symlink(r,n,e)},rename(e,t){var r,n,o=PATH.dirname(e),a=PATH.dirname(t),s=PATH.basename(e),i=PATH.basename(t);if(r=FS.lookupPath(e,{parent:!0}).node,n=FS.lookupPath(t,{parent:!0}).node,!r||!n)throw new FS.ErrnoError(44);if(r.mount!==n.mount)throw new FS.ErrnoError(75);var l,c=FS.lookupNode(r,s),u=PATH_FS.relative(e,a);if("."!==u.charAt(0))throw new FS.ErrnoError(28);if("."!==(u=PATH_FS.relative(t,o)).charAt(0))throw new FS.ErrnoError(55);try{l=FS.lookupNode(n,i)}catch(e){}if(c!==l){var m=FS.isDir(c.mode),d=FS.mayDelete(r,s,m);if(d)throw new FS.ErrnoError(d);if(d=l?FS.mayDelete(n,i,m):FS.mayCreate(n,i))throw new FS.ErrnoError(d);if(!r.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(c)||l&&FS.isMountpoint(l))throw new FS.ErrnoError(10);if(n!==r&&(d=FS.nodePermissions(r,"w")))throw new FS.ErrnoError(d);FS.hashRemoveNode(c);try{r.node_ops.rename(c,n,i)}catch(e){throw e}finally{FS.hashAddNode(c)}}},rmdir(e){var t=FS.lookupPath(e,{parent:!0}).node,r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!0);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.rmdir(t,r),FS.destroyNode(n)},readdir(e){var t=FS.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new FS.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=FS.lookupPath(e,{parent:!0}).node;if(!t)throw new FS.ErrnoError(44);var r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!1);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.unlink(t,r),FS.destroyNode(n)},readlink(e){var t=FS.lookupPath(e).node;if(!t)throw new FS.ErrnoError(44);if(!t.node_ops.readlink)throw new FS.ErrnoError(28);return PATH_FS.resolve(FS.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var r=FS.lookupPath(e,{follow:!t}).node;if(!r)throw new FS.ErrnoError(44);if(!r.node_ops.getattr)throw new FS.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>FS.stat(e,!0),chmod(e,t,r){var n;"string"==typeof e?n=FS.lookupPath(e,{follow:!r}).node:n=e;if(!n.node_ops.setattr)throw new FS.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&t|-4096&n.mode,timestamp:Date.now()})},lchmod(e,t){FS.chmod(e,t,!0)},fchmod(e,t){var r=FS.getStreamChecked(e);FS.chmod(r.node,t)},chown(e,t,r,n){var o;"string"==typeof e?o=FS.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new FS.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,r){FS.chown(e,t,r,!0)},fchown(e,t,r){var n=FS.getStreamChecked(e);FS.chown(n.node,t,r)},truncate(e,t){if(t<0)throw new FS.ErrnoError(28);var r;"string"==typeof e?r=FS.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(r.mode))throw new FS.ErrnoError(31);if(!FS.isFile(r.mode))throw new FS.ErrnoError(28);var n=FS.nodePermissions(r,"w");if(n)throw new FS.ErrnoError(n);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate(e,t){var r=FS.getStreamChecked(e);if(!(2097155&r.flags))throw new FS.ErrnoError(28);FS.truncate(r.node,t)},utime(e,t,r){var n=FS.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(t,r)})},open(e,t,r){if(""===e)throw new FS.ErrnoError(44);var n;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?FS_modeStringToFlags(t):t)?4095&r|32768:0,"object"==typeof e)n=e;else{e=PATH.normalize(e);try{n=FS.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(n){if(128&t)throw new FS.ErrnoError(20)}else n=FS.mknod(e,r,0),o=!0;if(!n)throw new FS.ErrnoError(44);if(FS.isChrdev(n.mode)&&(t&=-513),65536&t&&!FS.isDir(n.mode))throw new FS.ErrnoError(54);if(!o){var a=FS.mayOpen(n,t);if(a)throw new FS.ErrnoError(a)}512&t&&!o&&FS.truncate(n,0),t&=-131713;var s=FS.createStream({node:n,path:FS.getPath(n),flags:t,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!Module.logReadFiles||1&t||(FS.readFiles||(FS.readFiles={}),e in FS.readFiles||(FS.readFiles[e]=1)),s},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{FS.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read(e,t,r,n,o){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(1==(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var s=e.stream_ops.read(e,t,r,n,o);return a||(e.position+=s),s},write(e,t,r,n,o,a){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&1024&e.flags&&FS.llseek(e,0,2);var s=void 0!==o;if(s){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var i=e.stream_ops.write(e,t,r,n,o,a);return s||(e.position+=i),i},allocate(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(t<0||r<=0)throw new FS.ErrnoError(28);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap(e,t,r,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new FS.ErrnoError(2);if(1==(2097155&e.flags))throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);return e.stream_ops.mmap(e,t,r,n,o)},msync:(e,t,r,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,n,o):0,munmap:e=>0,ioctl(e,t,r){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var r,n=FS.open(e,t.flags),o=FS.stat(e).size,a=new Uint8Array(o);return FS.read(n,a,0,o,0),"utf8"===t.encoding?r=UTF8ArrayToString(a,0):"binary"===t.encoding&&(r=a),FS.close(n),r},writeFile(e,t,r={}){r.flags=r.flags||577;var n=FS.open(e,r.flags,r.mode);if("string"==typeof t){var o=new Uint8Array(lengthBytesUTF8(t)+1),a=stringToUTF8Array(t,o,0,o.length);FS.write(n,o,0,a,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");FS.write(n,t,0,t.byteLength,void 0,r.canOwn)}FS.close(n)},cwd:()=>FS.currentPath,chdir(e){var t=FS.lookupPath(e,{follow:!0});if(null===t.node)throw new FS.ErrnoError(44);if(!FS.isDir(t.node.mode))throw new FS.ErrnoError(54);var r=FS.nodePermissions(t.node,"x");if(r)throw new FS.ErrnoError(r);FS.currentPath=t.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(e,t,r,n,o)=>n}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=randomFill(e).byteLength),e[--t]);FS.createDevice("/dev","random",r),FS.createDevice("/dev","urandom",r),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var t=FS.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var r=+t,n=FS.getStreamChecked(r),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(){Module.stdin?FS.createDevice("/dev","stdin",Module.stdin):FS.symlink("/dev/tty","/dev/stdin"),Module.stdout?FS.createDevice("/dev","stdout",null,Module.stdout):FS.symlink("/dev/tty","/dev/stdout"),Module.stderr?FS.createDevice("/dev","stderr",null,Module.stderr):FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},ensureErrnoError(){FS.ErrnoError||(FS.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},FS.ErrnoError.prototype=new Error,FS.ErrnoError.prototype.constructor=FS.ErrnoError,[44].forEach(e=>{FS.genericErrors[e]=new FS.ErrnoError(e),FS.genericErrors[e].stack=""}))},staticInit(){FS.ensureErrnoError(),FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS:MEMFS}},init(e,t,r){FS.init.initialized=!0,FS.ensureErrnoError(),Module.stdin=e||Module.stdin,Module.stdout=t||Module.stdout,Module.stderr=r||Module.stderr,FS.createStandardStreams()},quit(){FS.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,n=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,s=1048576;o||(s=n);var i=this;i.setDataGetter(e=>{var t=e*s,o=(e+1)*s-1;if(o=Math.min(o,n-1),void 0===i.chunks[e]&&(i.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),n!==s&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):intArrayFromString(o.responseText||"",!0)})(t,o)),void 0===i.chunks[e])throw new Error("doXHR failed!");return i.chunks[e]}),!a&&n||(s=n=1,n=this.getter(0).length,s=n,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new a;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var i={isDevice:!1,contents:s}}else i={isDevice:!1,url:r};var l=FS.createFile(e,t,i,n,o);i.contents?l.contents=i.contents:i.url&&(l.contents=null,l.url=i.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,r,n,o){var a=e.node.contents;if(o>=a.length)return 0;var s=Math.min(a.length-o,n);if(a.slice)for(var i=0;i{var t=l.stream_ops[e];c[e]=function(){return FS.forceLoadFile(l),t.apply(null,arguments)}}),c.read=(e,t,r,n,o)=>(FS.forceLoadFile(l),u(e,t,r,n,o)),c.mmap=(e,t,r,n,o)=>{FS.forceLoadFile(l);var a=mmapAlloc(t);if(!a)throw new FS.ErrnoError(48);return u(e,HEAP8,a,t,r),{ptr:a,allocated:!0}},l.stream_ops=c,l}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,t,r){if(PATH.isAbs(t))return t;var n;-100===e?n=FS.cwd():n=SYSCALLS.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new FS.ErrnoError(44);return n}return PATH.join2(n,t)},doStat(e,t,r){try{var n=e(t)}catch(e){if(e&&e.node&&PATH.normalize(t)!==PATH.normalize(FS.getPath(e.node)))return-54;throw e}HEAP32[r>>2]=n.dev,HEAP32[r+4>>2]=n.mode,HEAPU32[r+8>>2]=n.nlink,HEAP32[r+12>>2]=n.uid,HEAP32[r+16>>2]=n.gid,HEAP32[r+20>>2]=n.rdev,tempI64=[n.size>>>0,(tempDouble=n.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+24>>2]=tempI64[0],HEAP32[r+28>>2]=tempI64[1],HEAP32[r+32>>2]=4096,HEAP32[r+36>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),s=n.ctime.getTime();return tempI64=[Math.floor(o/1e3)>>>0,(tempDouble=Math.floor(o/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+40>>2]=tempI64[0],HEAP32[r+44>>2]=tempI64[1],HEAPU32[r+48>>2]=o%1e3*1e3,tempI64=[Math.floor(a/1e3)>>>0,(tempDouble=Math.floor(a/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+56>>2]=tempI64[0],HEAP32[r+60>>2]=tempI64[1],HEAPU32[r+64>>2]=a%1e3*1e3,tempI64=[Math.floor(s/1e3)>>>0,(tempDouble=Math.floor(s/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+72>>2]=tempI64[0],HEAP32[r+76>>2]=tempI64[1],HEAPU32[r+80>>2]=s%1e3*1e3,tempI64=[n.ino>>>0,(tempDouble=n.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+88>>2]=tempI64[0],HEAP32[r+92>>2]=tempI64[1],0},doMsync(e,t,r,n,o){if(!FS.isFile(t.node.mode))throw new FS.ErrnoError(43);if(2&n)return 0;var a=HEAPU8.slice(e,e+r);FS.msync(t,a,o,r,n)},varargs:void 0,get(){var e=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},getp:()=>SYSCALLS.get(),getStr:e=>UTF8ToString(e),getStreamFromFD:e=>FS.getStreamChecked(e)};function ___syscall__newselect(e,t,r,n,o){try{for(var a=0,s=t?HEAP32[t>>2]:0,i=t?HEAP32[t+4>>2]:0,l=r?HEAP32[r>>2]:0,c=r?HEAP32[r+4>>2]:0,u=n?HEAP32[n>>2]:0,m=n?HEAP32[n+4>>2]:0,d=0,_=0,f=0,p=0,S=0,g=0,E=(t?HEAP32[t>>2]:0)|(r?HEAP32[r>>2]:0)|(n?HEAP32[n>>2]:0),h=(t?HEAP32[t+4>>2]:0)|(r?HEAP32[r+4>>2]:0)|(n?HEAP32[n+4>>2]:0),v=function(e,t,r,n){return e<32?t&n:r&n},F=0;F>2]:0)+(t?HEAP32[o+8>>2]:0)/1e6);D=w.stream_ops.poll(w,b)}1&D&&v(F,s,i,y)&&(F<32?d|=y:_|=y,a++),4&D&&v(F,l,c,y)&&(F<32?f|=y:p|=y,a++),2&D&&v(F,u,m,y)&&(F<32?S|=y:g|=y,a++)}}return t&&(HEAP32[t>>2]=d,HEAP32[t+4>>2]=_),r&&(HEAP32[r>>2]=f,HEAP32[r+4>>2]=p),n&&(HEAP32[n>>2]=S,HEAP32[n+4>>2]=g),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var SOCKFS={mount:e=>(Module.websocket=Module.websocket&&"object"==typeof Module.websocket?Module.websocket:{},Module.websocket._callbacks={},Module.websocket.on=function(e,t){return"function"==typeof t&&(this._callbacks[e]=t),this},Module.websocket.emit=function(e,t){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,t)},FS.createNode(null,"/",16895,0)),createSocket(e,t,r){if(1==(t&=-526337)&&r&&6!=r)throw new FS.ErrnoError(66);var n={family:e,type:t,protocol:r,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},o=SOCKFS.nextname(),a=FS.createNode(SOCKFS.root,o,49152,0);a.sock=n;var s=FS.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return n.stream=s,n},getSocket(e){var t=FS.getStream(e);return t&&FS.isSocket(t.node.mode)?t.node.sock:null},stream_ops:{poll(e){var t=e.node.sock;return t.sock_ops.poll(t)},ioctl(e,t,r){var n=e.node.sock;return n.sock_ops.ioctl(n,t,r)},read(e,t,r,n,o){var a=e.node.sock,s=a.sock_ops.recvmsg(a,n);return s?(t.set(s.buffer,r),s.buffer.length):0},write(e,t,r,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,t,r,n)},close(e){var t=e.node.sock;t.sock_ops.close(t)}},nextname:()=>(SOCKFS.nextname.current||(SOCKFS.nextname.current=0),"socket["+SOCKFS.nextname.current+++"]"),websocket_sock_ops:{createPeer(e,t,r){var n;if("object"==typeof t&&(n=t,t=null,r=null),n)if(n._socket)t=n._socket.remoteAddress,r=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");t=o[1],r=parseInt(o[2],10)}else try{var a=Module.websocket&&"object"==typeof Module.websocket,s="ws:#".replace("#","//");if(a&&"string"==typeof Module.websocket.url&&(s=Module.websocket.url),"ws://"===s||"wss://"===s){var i=t.split("/");s=s+i[0]+":"+r+"/"+i.slice(1).join("/")}var l="binary";a&&"string"==typeof Module.websocket.subprotocol&&(l=Module.websocket.subprotocol);var c=void 0;"null"!==l&&(c=l=l.replace(/^ +| +$/g,"").split(/ *, */)),a&&null===Module.websocket.subprotocol&&(l="null",c=void 0),(n=new WebSocket(s,c)).binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}var u={addr:t,port:r,socket:n,dgram_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,u),SOCKFS.websocket_sock_ops.handlePeerEvents(e,u),2===e.type&&void 0!==e.sport&&u.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),u},getPeer:(e,t,r)=>e.peers[t+":"+r],addPeer(e,t){e.peers[t.addr+":"+t.port]=t},removePeer(e,t){delete e.peers[t.addr+":"+t.port]},handlePeerEvents(e,t){var r=!0,n=function(){Module.websocket.emit("open",e.stream.fd);try{for(var r=t.dgram_send_queue.shift();r;)t.socket.send(r),r=t.dgram_send_queue.shift()}catch(e){t.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(assert(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=r;if(r=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var a=n[8]<<8|n[9];return SOCKFS.websocket_sock_ops.removePeer(e,t),t.port=a,void SOCKFS.websocket_sock_ops.addPeer(e,t)}e.recv_queue.push({addr:t.addr,port:t.port,data:n}),Module.websocket.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(t.socket.on("open",n),t.socket.on("message",function(e,t){t&&o(new Uint8Array(e).buffer)}),t.socket.on("close",function(){Module.websocket.emit("close",e.stream.fd)}),t.socket.on("error",function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(t.socket.onopen=n,t.socket.onclose=function(){Module.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){o(e.data)},t.socket.onerror=function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(1===e.type&&e.server)return e.pending.length?65:0;var t=0,r=1===e.type?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!r||r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=65),(!r||r&&r.socket.readyState===r.socket.OPEN)&&(t|=4),(r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=16),t},ioctl(e,t,r){if(21531===t){var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),HEAP32[r>>2]=n,0}return 28},close(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var t=Object.keys(e.peers),r=0;r{var t=SOCKFS.getSocket(e);if(!t)throw new FS.ErrnoError(8);return t},setErrNo=e=>(HEAP32[___errno_location()>>2]=e,e),inetNtop4=e=>(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var t="",r=0,n=0,o=0,a=0,s=0,i=0,l=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,u="";for(i=0;i<5;i++)if(0!==l[i]){c=!1;break}if(c){if(u=inetNtop4(l[6]|l[7]<<16),-1===l[5])return t="::ffff:",t+=u;if(0===l[5])return t="::","0.0.0.0"===u&&(u=""),"0.0.0.1"===u&&(u="1"),t+=u}for(r=0;r<8;r++)0===l[r]&&(r-o>1&&(s=0),o=r,s++),s>n&&(a=r-(n=s)+1);for(r=0;r<8;r++)n>1&&0===l[r]&&r>=a&&r{var r,n=HEAP16[e>>1],o=_ntohs(HEAPU16[e+2>>1]);switch(n){case 2:if(16!==t)return{errno:28};r=HEAP32[e+4>>2],r=inetNtop4(r);break;case 10:if(28!==t)return{errno:28};r=[HEAP32[e+8>>2],HEAP32[e+12>>2],HEAP32[e+16>>2],HEAP32[e+20>>2]],r=inetNtop6(r);break;default:return{errno:5}}return{family:n,addr:r,port:o}},inetPton4=e=>{for(var t=e.split("."),r=0;r<4;r++){var n=Number(t[r]);if(isNaN(n))return null;t[r]=n}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var t,r,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jstoi_q(t[t.length-4])+256*jstoi_q(t[t.length-3]),t[t.length-3]=jstoi_q(t[t.length-2])+256*jstoi_q(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),n=0,o=0,r=0;rDNS.address_map.names[e]?DNS.address_map.names[e]:null},getSocketAddress=(e,t,r)=>{if(r&&0===e)return null;var n=readSockaddr(e,t);if(n.errno)throw new FS.ErrnoError(n.errno);return n.addr=DNS.lookup_addr(n.addr)||n.addr,n};function ___syscall_connect(e,t,r,n,o,a){try{var s=getSocketFromFD(e),i=getSocketAddress(t,r);return s.sock_ops.connect(s,i.addr,i.port),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_faccessat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),-8&r)return-28;var o=FS.lookupPath(t,{follow:!0}).node;if(!o)return-44;var a="";return 4&r&&(a+="r"),2&r&&(a+="w"),1&r&&(a+="x"),a&&FS.nodePermissions(o,a)?-2:0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fcntl64(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 0:if((o=SYSCALLS.get())<0)return-28;for(;FS.streams[o];)o++;return FS.createStream(n,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return n.flags;case 4:var o=SYSCALLS.get();return n.flags|=o,0;case 5:o=SYSCALLS.getp();return HEAP16[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return setErrNo(28),-1}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fstat64(e,t){try{var r=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,r.path,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var stringToUTF8=(e,t,r)=>stringToUTF8Array(e,HEAPU8,t,r);function ___syscall_getcwd(e,t){try{if(0===t)return-28;var r=FS.cwd(),n=lengthBytesUTF8(r)+1;return t>>0,(tempDouble=l,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t+a>>2]=tempI64[0],HEAP32[t+a+4>>2]=tempI64[1],tempI64=[(i+1)*o>>>0,(tempDouble=(i+1)*o,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t+a+8>>2]=tempI64[0],HEAP32[t+a+12>>2]=tempI64[1],HEAP16[t+a+16>>1]=280,HEAP8[t+a+18|0]=c,stringToUTF8(u,t+a+19,256),a+=o,i+=1}return FS.llseek(n,i*o,0),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_ioctl(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return n.tty?0:-59;case 21505:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var o=n.tty.ops.ioctl_tcgets(n),a=SYSCALLS.getp();HEAP32[a>>2]=o.c_iflag||0,HEAP32[a+4>>2]=o.c_oflag||0,HEAP32[a+8>>2]=o.c_cflag||0,HEAP32[a+12>>2]=o.c_lflag||0;for(var s=0;s<32;s++)HEAP8[a+s+17|0]=o.c_cc[s]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){a=SYSCALLS.getp();var i=HEAP32[a>>2],l=HEAP32[a+4>>2],c=HEAP32[a+8>>2],u=HEAP32[a+12>>2],m=[];for(s=0;s<32;s++)m.push(HEAP8[a+s+17|0]);return n.tty.ops.ioctl_tcsets(n.tty,t,{c_iflag:i,c_oflag:l,c_cflag:c,c_lflag:u,c_cc:m})}return 0;case 21519:if(!n.tty)return-59;a=SYSCALLS.getp();return HEAP32[a>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:a=SYSCALLS.getp();return FS.ioctl(n,t,a);case 21523:if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var d=n.tty.ops.ioctl_tiocgwinsz(n.tty);a=SYSCALLS.getp();HEAP16[a>>1]=d[0],HEAP16[a+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_lstat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.lstat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_mkdirat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),"/"===(t=PATH.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),FS.mkdir(t,r,0),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_newfstatat(e,t,r,n){try{t=SYSCALLS.getStr(t);var o=256&n,a=4096&n;return n&=-6401,t=SYSCALLS.calculateAt(e,t,a),SYSCALLS.doStat(o?FS.lstat:FS.stat,t,r)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_openat(e,t,r,n){SYSCALLS.varargs=n;try{t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t);var o=n?SYSCALLS.get():0;return FS.open(t,r,o).fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_readlinkat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),n<=0)return-28;var o=FS.readlink(t),a=Math.min(n,lengthBytesUTF8(o)),s=HEAP8[r+a];return stringToUTF8(o,r,n+1),HEAP8[r+a]=s,a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_rmdir(e){try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_socket(e,t,r){try{return SOCKFS.createSocket(e,t,r).stream.fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_stat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_unlinkat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),0===r?FS.unlink(t):512===r?FS.rmdir(t):abort("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var nowIsMonotonic=!0,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic,convertI32PairToI53Checked=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN;function __gmtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getUTCSeconds(),HEAP32[r+4>>2]=o.getUTCMinutes(),HEAP32[r+8>>2]=o.getUTCHours(),HEAP32[r+12>>2]=o.getUTCDate(),HEAP32[r+16>>2]=o.getUTCMonth(),HEAP32[r+20>>2]=o.getUTCFullYear()-1900,HEAP32[r+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),s=(o.getTime()-a)/864e5|0;HEAP32[r+28>>2]=s}var isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>(isLeapYear(e.getFullYear())?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()]+e.getDate()-1;function __localtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getSeconds(),HEAP32[r+4>>2]=o.getMinutes(),HEAP32[r+8>>2]=o.getHours(),HEAP32[r+12>>2]=o.getDate(),HEAP32[r+16>>2]=o.getMonth(),HEAP32[r+20>>2]=o.getFullYear()-1900,HEAP32[r+24>>2]=o.getDay();var a=0|ydayFromDate(o);HEAP32[r+28>>2]=a,HEAP32[r+36>>2]=-60*o.getTimezoneOffset();var s=new Date(o.getFullYear(),0,1),i=new Date(o.getFullYear(),6,1).getTimezoneOffset(),l=s.getTimezoneOffset(),c=0|(i!=l&&o.getTimezoneOffset()==Math.min(l,i));HEAP32[r+32>>2]=c}var __mktime_js=function(e){var t=(()=>{var t=new Date(HEAP32[e+20>>2]+1900,HEAP32[e+16>>2],HEAP32[e+12>>2],HEAP32[e+8>>2],HEAP32[e+4>>2],HEAP32[e>>2],0),r=HEAP32[e+32>>2],n=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),i=Math.min(s,a);if(r<0)HEAP32[e+32>>2]=Number(a!=s&&i==n);else if(r>0!=(i==n)){var l=Math.max(s,a),c=r>0?i:l;t.setTime(t.getTime()+6e4*(c-n))}HEAP32[e+24>>2]=t.getDay();var u=0|ydayFromDate(t);return HEAP32[e+28>>2]=u,HEAP32[e>>2]=t.getSeconds(),HEAP32[e+4>>2]=t.getMinutes(),HEAP32[e+8>>2]=t.getHours(),HEAP32[e+12>>2]=t.getDate(),HEAP32[e+16>>2]=t.getMonth(),HEAP32[e+20>>2]=t.getYear(),t.getTime()/1e3})();return setTempRet0((tempDouble=t,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)),t>>>0};function __mmap_js(e,t,r,n,o,a,s,i){var l=convertI32PairToI53Checked(o,a);try{if(isNaN(l))return 61;var c=SYSCALLS.getStreamFromFD(n),u=FS.mmap(c,e,l,t,r),m=u.ptr;return HEAP32[s>>2]=u.allocated,HEAPU32[i>>2]=m,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function __munmap_js(e,t,r,n,o,a,s){var i=convertI32PairToI53Checked(a,s);try{if(isNaN(i))return 61;var l=SYSCALLS.getStreamFromFD(o);2&r&&SYSCALLS.doMsync(e,l,t,n,i),FS.munmap(l)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var _emscripten_get_now,stringToNewUTF8=e=>{var t=lengthBytesUTF8(e)+1,r=_malloc(t);return r&&stringToUTF8(e,r,t),r},__tzset_js=(e,t,r)=>{var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),s=o.getTimezoneOffset(),i=a.getTimezoneOffset(),l=Math.max(s,i);function c(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}HEAPU32[e>>2]=60*l,HEAP32[t>>2]=Number(s!=i);var u=c(o),m=c(a),d=stringToNewUTF8(u),_=stringToNewUTF8(m);i>2]=d,HEAPU32[r+4>>2]=_):(HEAPU32[r>>2]=_,HEAPU32[r+4>>2]=d)},_abort=()=>{abort("")},readEmAsmArgsArray=[],readEmAsmArgs=(e,t)=>{var r;for(readEmAsmArgsArray.length=0;r=HEAPU8[e++];){var n=105!=r;t+=(n&=112!=r)&&t%8?4:0,readEmAsmArgsArray.push(112==r?HEAPU32[t>>2]:105==r?HEAP32[t>>2]:HEAPF64[t>>3]),t+=n?8:4}return readEmAsmArgsArray},runEmAsmFunction=(e,t,r)=>{var n=readEmAsmArgs(t,r);return ASM_CONSTS[e].apply(null,n)},_emscripten_asm_const_int=(e,t,r)=>runEmAsmFunction(e,t,r),_emscripten_date_now=()=>Date.now(),_emscripten_errn=(e,t)=>err(UTF8ToString(e,t)),getHeapMax=()=>2147483648,_emscripten_get_heap_max=()=>getHeapMax();_emscripten_get_now=()=>performance.now();var reallyNegative=e=>e<0||0===e&&1/e==-1/0,convertI32PairToI53=(e,t)=>(e>>>0)+4294967296*t,convertU32PairToI53=(e,t)=>(e>>>0)+4294967296*(t>>>0),reSign=(e,t)=>{if(e<=0)return e;var r=t<=32?Math.abs(1<=r&&(t<=32||e>r)&&(e=-2*r+e),e},unSign=(e,t)=>e>=0?e:t<=32?2*Math.abs(1<{for(var t=e;HEAPU8[t];)++t;return t-e},formatString=(e,t)=>{var r=e,n=t;function o(e){var t;return n=function(e,t){return"double"!==t&&"i64"!==t||7&e&&(e+=4),e}(n,e),"double"===e?(t=HEAPF64[n>>3],n+=8):"i64"==e?(t=[HEAP32[n>>2],HEAP32[n+4>>2]],n+=8):(e="i32",t=HEAP32[n>>2],n+=4),t}for(var a,s,i,l=[];;){var c=r;if(0===(a=HEAP8[r|0]))break;if(s=HEAP8[r+1|0],37==a){var u=!1,m=!1,d=!1,_=!1,f=!1;e:for(;;){switch(s){case 43:u=!0;break;case 45:m=!0;break;case 35:d=!0;break;case 48:if(_)break e;_=!0;break;case 32:f=!0;break;default:break e}r++,s=HEAP8[r+1|0]}var p=0;if(42==s)p=o("i32"),r++,s=HEAP8[r+1|0];else for(;s>=48&&s<=57;)p=10*p+(s-48),r++,s=HEAP8[r+1|0];var S,g=!1,E=-1;if(46==s){if(E=0,g=!0,r++,42==(s=HEAP8[r+1|0]))E=o("i32"),r++;else for(;;){var h=HEAP8[r+1|0];if(h<48||h>57)break;E=10*E+(h-48),r++}s=HEAP8[r+1|0]}switch(E<0&&(E=6,g=!1),String.fromCharCode(s)){case"h":104==HEAP8[r+2|0]?(r++,S=1):S=2;break;case"l":108==HEAP8[r+2|0]?(r++,S=8):S=4;break;case"L":case"q":case"j":S=8;break;case"z":case"t":case"I":S=4;break;default:S=null}switch(S&&r++,s=HEAP8[r+1|0],String.fromCharCode(s)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":var v=100==s||105==s;if(i=o("i"+8*(S=S||4)),8==S&&(i=117==s?convertU32PairToI53(i[0],i[1]):convertI32PairToI53(i[0],i[1])),S<=4){var F=Math.pow(256,S)-1;i=(v?reSign:unSign)(i&F,8*S)}var y=Math.abs(i),w="";if(100==s||105==s)k=reSign(i,8*S).toString(10);else if(117==s)k=unSign(i,8*S).toString(10),i=Math.abs(i);else if(111==s)k=(d?"0":"")+y.toString(8);else if(120==s||88==s){if(w=d&&0!=i?"0x":"",i<0){i=-i,k=(y-1).toString(16);for(var D=[],b=0;b=0&&(u?w="+"+w:f&&(w=" "+w)),"-"==k.charAt(0)&&(w="-"+w,k=k.substr(1));w.length+k.lengthN&&N>=-4?(s=(103==s?"f":"F").charCodeAt(0),E-=N+1):(s=(103==s?"e":"E").charCodeAt(0),E--),T=Math.min(E,20)}101==s||69==s?(k=i.toExponential(T),/[eE][-+]\d$/.test(k)&&(k=k.slice(0,-1)+"0"+k.slice(-1))):102!=s&&70!=s||(k=i.toFixed(T),0===i&&reallyNegative(i)&&(k="-"+k));var P=k.split("e");if(A&&!d)for(;P[0].length>1&&P[0].includes(".")&&("0"==P[0].slice(-1)||"."==P[0].slice(-1));)P[0]=P[0].slice(0,-1);else for(d&&-1==k.indexOf(".")&&(P[0]+=".");E>T++;)P[0]+="0";k=P[0]+(P.length>1?"e"+P[1]:""),69==s&&(k=k.toUpperCase()),i>=0&&(u?k="+"+k:f&&(k=" "+k))}else k=(i<0?"-":"")+"inf",_=!1;for(;k.length0;)l.push(32);m||l.push(o("i8"));break;case"n":var M=o("i32*");HEAP32[M>>2]=l.length;break;case"%":l.push(a);break;default:for(b=c;b{warnOnce.shown||(warnOnce.shown={}),warnOnce.shown[e]||(warnOnce.shown[e]=1,err(e))};function getCallstack(e){var t=jsStackTrace(),r=t.lastIndexOf("_emscripten_log"),n=t.lastIndexOf("_emscripten_get_callstack"),o=t.indexOf("\n",Math.max(r,n))+1;t=t.slice(o),8&e&&"undefined"==typeof emscripten_source_map&&(warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'),e^=8,e|=16);var a=t.split("\n");t="";var s=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"),i=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"),l=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var c in a){var u=a[c],m="",d="",_=0,f=0,p=l.exec(u);if(p&&5==p.length)m=p[1],d=p[2],_=p[3],f=p[4];else{if((p=s.exec(u))||(p=i.exec(u)),!(p&&p.length>=4)){t+=u+"\n";continue}m=p[1],d=p[2],_=p[3],f=0|p[4]}var S=!1;if(8&e){var g=emscripten_source_map.originalPositionFor({line:_,column:f});(S=g&&g.source)&&(64&e&&(g.source=g.source.substring(g.source.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=` at ${m} (${g.source}:${g.line}:${g.column})\n`)}(16&e||!S)&&(64&e&&(d=d.substring(d.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=(S?` = ${m}`:` at ${m}`)+` (${d}:${_}:${f})\n`)}return t=t.replace(/\s+$/,"")}var emscriptenLog=(e,t)=>{24&e&&(t=t.replace(/\s+$/,""),t+=(t.length>0?"\n":"")+getCallstack(e)),1&e?4&e||2&e?err(t):out(t):6&e?err(t):out(t)},_emscripten_log=(e,t,r)=>{var n=formatString(t,r),o=UTF8ArrayToString(n,0);emscriptenLog(e,o)},growMemory=e=>{var t=(e-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch(e){}},_emscripten_resize_heap=e=>{var t=HEAPU8.length;e>>>=0;var r=getHeapMax();if(e>r)return!1;for(var n=(e,t)=>e+(t-e%t)%t,o=1;o<=4;o*=2){var a=t*(1+.2/o);a=Math.min(a,e+100663296);var s=Math.min(r,n(Math.max(e,a),65536));if(growMemory(s))return!0}return!1},ENV={},getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(var t in ENV)void 0===ENV[t]?delete e[t]:e[t]=ENV[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToAscii=(e,t)=>{for(var r=0;r{var r=0;return getEnvStrings().forEach((n,o)=>{var a=t+r;HEAPU32[e+4*o>>2]=a,stringToAscii(n,a),r+=n.length+1}),0},_environ_sizes_get=(e,t)=>{var r=getEnvStrings();HEAPU32[e>>2]=r.length;var n=0;return r.forEach(e=>n+=e.length+1),HEAPU32[t>>2]=n,0};function _fd_close(e){try{var t=SYSCALLS.getStreamFromFD(e);return FS.close(t),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doReadv=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.read(e,HEAP8,s,i,n);if(l<0)return-1;if(o+=l,l>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}function _fd_seek(e,t,r,n,o){var a=convertI32PairToI53Checked(t,r);try{if(isNaN(a))return 61;var s=SYSCALLS.getStreamFromFD(e);return FS.llseek(s,a,n),tempI64=[s.position>>>0,(tempDouble=s.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[o>>2]=tempI64[0],HEAP32[o+4>>2]=tempI64[1],s.getdents&&0===a&&0===n&&(s.getdents=null),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doWritev=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.write(e,HEAP8,s,i,n);if(l<0)return-1;o+=l,void 0!==n&&(n+=l)}return o};function _fd_write(e,t,r,n){try{var o=SYSCALLS.getStreamFromFD(e),a=doWritev(o,t,r);return HEAPU32[n>>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var wasmTable,functionsInTableMap,arraySum=(e,t)=>{for(var r=0,n=0;n<=t;r+=e[n++]);return r},MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31],MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31],addDays=(e,t)=>{for(var r=new Date(e.getTime());t>0;){var n=isLeapYear(r.getFullYear()),o=r.getMonth(),a=(n?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[o];if(!(t>a-r.getDate()))return r.setDate(r.getDate()+t),r;t-=a-r.getDate()+1,r.setDate(1),o<11?r.setMonth(o+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r},writeArrayToMemory=(e,t)=>{HEAP8.set(e,t)},_strftime=(e,t,r,n)=>{var o=HEAPU32[n+40>>2],a={tm_sec:HEAP32[n>>2],tm_min:HEAP32[n+4>>2],tm_hour:HEAP32[n+8>>2],tm_mday:HEAP32[n+12>>2],tm_mon:HEAP32[n+16>>2],tm_year:HEAP32[n+20>>2],tm_wday:HEAP32[n+24>>2],tm_yday:HEAP32[n+28>>2],tm_isdst:HEAP32[n+32>>2],tm_gmtoff:HEAP32[n+36>>2],tm_zone:o?UTF8ToString(o):""},s=UTF8ToString(r),i={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in i)s=s.replace(new RegExp(l,"g"),i[l]);var c=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"];function m(e,t,r){for(var n="number"==typeof e?e.toString():e||"";n.length0?1:0}var n;return 0===(n=r(e.getFullYear()-t.getFullYear()))&&0===(n=r(e.getMonth()-t.getMonth()))&&(n=r(e.getDate()-t.getDate())),n}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function p(e){var t=addDays(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),n=new Date(t.getFullYear()+1,0,4),o=f(r),a=f(n);return _(o,t)<=0?_(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var S={"%a":e=>c[e.tm_wday].substring(0,3),"%A":e=>c[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>d((e.tm_year+1900)/100|0,2),"%d":e=>d(e.tm_mday,2),"%e":e=>m(e.tm_mday,2," "),"%g":e=>p(e).toString().substring(2),"%G":e=>p(e),"%H":e=>d(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":e=>d(e.tm_mday+arraySum(isLeapYear(e.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,e.tm_mon-1),3),"%m":e=>d(e.tm_mon+1,2),"%M":e=>d(e.tm_min,2),"%n":()=>"\n","%p":e=>e.tm_hour>=0&&e.tm_hour<12?"AM":"PM","%S":e=>d(e.tm_sec,2),"%t":()=>"\t","%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&isLeapYear(e.tm_year)||(t=1)}}else{t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(4==n||5==n&&isLeapYear(e.tm_year%400-1))&&t++}return d(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>"%"};for(var l in s=s.replace(/%%/g,"\0\0"),S)s.includes(l)&&(s=s.replace(new RegExp(l,"g"),S[l](a)));var g=intArrayFromString(s=s.replace(/\0\0/g,"%"),!1);return g.length>t?0:(writeArrayToMemory(g,e),g.length-1)},_strftime_l=(e,t,r,n,o)=>_strftime(e,t,r,n),getWasmTableEntry=e=>wasmTable.get(e),uleb128Encode=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var t={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"},r={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},n=1;n{var r=e.slice(0,1),n=e.slice(1),o={i:127,p:127,j:126,f:125,d:124};t.push(96),uleb128Encode(n.length,t);for(var a=0;a{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function(sigToWasmTypes(t),e);var r=[1];generateFuncType(t,r);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(r.length,n),n.push.apply(n,r),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var o=new WebAssembly.Module(new Uint8Array(n));return new WebAssembly.Instance(o,{e:{f:e}}).exports.f},updateTableMap=(e,t)=>{if(functionsInTableMap)for(var r=e;r(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1},setWasmTableEntry=(e,t)=>wasmTable.set(e,t),addFunction=(e,t)=>{var r=getFunctionAddress(e);if(r)return r;var n=getEmptyTableSlot();try{setWasmTableEntry(n,e)}catch(r){if(!(r instanceof TypeError))throw r;var o=convertJsFunctionToWasm(e,t);setWasmTableEntry(n,o)}return functionsInTableMap.set(e,n),n},stringToUTF8OnStack=e=>{var t=lengthBytesUTF8(e)+1,r=stackAlloc(t);return stringToUTF8(e,r,t),r},FSNode=function(e,t,r,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=FS.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n},readMode=365,writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(e){e?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(e){e?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}}),FS.FSNode=FSNode,FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit();var calledRun,wasmImports={CreateDirectoryFetcher:_CreateDirectoryFetcher,DDN_ConvertElement:_DDN_ConvertElement,DDN_CreateDDNResult:_DDN_CreateDDNResult,DDN_CreateDDNResultItem:_DDN_CreateDDNResultItem,DDN_CreateIntermediateResultUnits:_DDN_CreateIntermediateResultUnits,DDN_CreateParameters:_DDN_CreateParameters,DDN_CreateTargetRoiDefConditionFilter:_DDN_CreateTargetRoiDefConditionFilter,DDN_CreateTaskAlgEntity:_DDN_CreateTaskAlgEntity,DDN_HasSection:_DDN_HasSection,DDN_ReadTaskSetting:_DDN_ReadTaskSetting,DLR_ConvertElement:_DLR_ConvertElement,DLR_CreateBufferedCharacterItemSet:_DLR_CreateBufferedCharacterItemSet,DLR_CreateIntermediateResultUnits:_DLR_CreateIntermediateResultUnits,DLR_CreateParameters:_DLR_CreateParameters,DLR_CreateRecognizedTextLinesResult:_DLR_CreateRecognizedTextLinesResult,DLR_CreateTargetRoiDefConditionFilter:_DLR_CreateTargetRoiDefConditionFilter,DLR_CreateTaskAlgEntity:_DLR_CreateTaskAlgEntity,DLR_CreateTextLineResultItem:_DLR_CreateTextLineResultItem,DLR_ReadTaskSetting:_DLR_ReadTaskSetting,DMImage_GetDIB:_DMImage_GetDIB,DMImage_GetOrientation:_DMImage_GetOrientation,DeleteDirectoryFetcher:_DeleteDirectoryFetcher,_ZN19LabelRecognizerWasm10getVersionEv:__ZN19LabelRecognizerWasm10getVersionEv,_ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv:__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv,_ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv:__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv,_ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi:__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi,_ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb:__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb,_ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb:__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb,_ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb:__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb,_ZN19LabelRecognizerWasm12DlrWasmClassC1Ev:__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev,_ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE:__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE,_ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE:__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE,_ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE:__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE,_ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE:__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE,_ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE:__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE,_ZN22DocumentNormalizerWasm10getVersionEv:__ZN22DocumentNormalizerWasm10getVersionEv,_ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv:__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv,_ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi:__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi,_ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii:__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii,_ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE,_ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev:__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev,_ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE:__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE,_ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE:__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE,_ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E:__ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E,_ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E:__ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E,_ZN9dynamsoft7utility14CUtilityModule10GetVersionEv:__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv,__assert_fail:___assert_fail,__cxa_begin_catch:___cxa_begin_catch,__cxa_end_catch:___cxa_end_catch,__cxa_find_matching_catch_2:___cxa_find_matching_catch_2,__cxa_find_matching_catch_3:___cxa_find_matching_catch_3,__cxa_rethrow:___cxa_rethrow,__cxa_rethrow_primary_exception:___cxa_rethrow_primary_exception,__cxa_throw:___cxa_throw,__cxa_uncaught_exceptions:___cxa_uncaught_exceptions,__resumeException:___resumeException,__syscall__newselect:___syscall__newselect,__syscall_connect:___syscall_connect,__syscall_faccessat:___syscall_faccessat,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_readlinkat:___syscall_readlinkat,__syscall_rmdir:___syscall_rmdir,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_unlinkat:___syscall_unlinkat,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_mktime_js:__mktime_js,_mmap_js:__mmap_js,_munmap_js:__munmap_js,_tzset_js:__tzset_js,abort:_abort,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_date_now:_emscripten_date_now,emscripten_errn:_emscripten_errn,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_log:_emscripten_log,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,invoke_diii:invoke_diii,invoke_fiii:invoke_fiii,invoke_i:invoke_i,invoke_ii:invoke_ii,invoke_iii:invoke_iii,invoke_iiii:invoke_iiii,invoke_iiiii:invoke_iiiii,invoke_iiiiid:invoke_iiiiid,invoke_iiiiii:invoke_iiiiii,invoke_iiiiiii:invoke_iiiiiii,invoke_iiiiiiii:invoke_iiiiiiii,invoke_iiiiiiiiiiii:invoke_iiiiiiiiiiii,invoke_iiiiij:invoke_iiiiij,invoke_j:invoke_j,invoke_ji:invoke_ji,invoke_jii:invoke_jii,invoke_jiiii:invoke_jiiii,invoke_v:invoke_v,invoke_vi:invoke_vi,invoke_vii:invoke_vii,invoke_viid:invoke_viid,invoke_viii:invoke_viii,invoke_viiii:invoke_viiii,invoke_viiiiiii:invoke_viiiiiii,invoke_viiiiiiiiii:invoke_viiiiiiiiii,invoke_viiiiiiiiiiiiiii:invoke_viiiiiiiiiiiiiii,strftime:_strftime,strftime_l:_strftime_l},wasmExports=createWasm();function invoke_iiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(e,t){var r=stackSave();try{return getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(e,t,r){var n=stackSave();try{return getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(e,t,r){var n=stackSave();try{getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(e,t,r,n,o){var a=stackSave();try{getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(e){var t=stackSave();try{getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(e,t,r,n,o){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(e,t){var r=stackSave();try{getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(e,t,r,n,o,a,s){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiid(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_diii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(e){var t=stackSave();try{return getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,m){var d=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,m)}catch(e){if(stackRestore(d),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u){var m=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u)}catch(e){if(stackRestore(m),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,m,d,_,f,p){var S=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,m,d,_,f,p)}catch(e){if(stackRestore(S),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_j(e){var t=stackSave();try{return dynCall_j(e)}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(e,t){var r=stackSave();try{return dynCall_ji(e,t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(e,t,r){var n=stackSave();try{return dynCall_jii(e,t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiij(e,t,r,n,o,a,s){var i=stackSave();try{return dynCall_iiiiij(e,t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(e,t,r,n,o){var a=stackSave();try{return dynCall_jiiii(e,t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function run(){function e(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT||(initRuntime(),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)]()[UTF8ToString(r)]()),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack((new(self[UTF8ToString(e)]))[UTF8ToString(t)](UTF8ToString(r))),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>{self[UTF8ToString(e)](null,UTF8ToString(t).trim(),UTF8ToString(r),n)},"viiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)][UTF8ToString(r)](UTF8ToString(n))?"":self[UTF8ToString(e)][UTF8ToString(t)]),"iiiii")),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun()))}runDependencies>0||(preRun(),runDependencies>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()))}if(Module.addFunction=addFunction,Module.stringToUTF8OnStack=stringToUTF8OnStack,dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)},Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();run(); \ No newline at end of file +var read_,readAsync,readBinary,Module=void 0!==Module?Module:{},moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(e,t)=>{throw t},ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!0,ENVIRONMENT_IS_NODE=!1,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:"undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=0!==scriptDirectory.indexOf("blob:")?scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1):"",read_=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var t=new XMLHttpRequest;t.open("GET",e,!1),t.responseType="arraybuffer";let r=Date.now();return t.onloadstart=()=>{postMessage({type:"event",id:-3,body:{loaded:0,total:pe.lengthComputable?pe.total:0,tag:"starting",resourcesPath:e}})},t.onprogress=t=>{const n=Date.now();r+500{postMessage({type:"event",id:-3,body:{loaded:pe.lengthComputable?pe.total:0,total:pe.lengthComputable?pe.total:0,tag:"completed",resourcesPath:e}})},t.send(null),new Uint8Array(t.response)}),readAsync=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var wasmBinary,out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit),Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,noExitRuntime=Module.noExitRuntime||!0;"object"!=typeof WebAssembly&&abort("no native wasm support detected");var EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,ABORT=!1;function assert(e,t){e||abort(t)}function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e)}var __ATPRERUN__=[],__ATINIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,Module.noFSInit||FS.init.initialized||FS.init(),FS.ignorePermissions=!1,TTY.init(),SOCKFS.root=FS.mount(SOCKFS,{},null),callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module.postRun)for("function"==typeof Module.postRun&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(e){return e}function addRunDependency(e){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}function removeRunDependency(e){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}function abort(e){throw Module.onAbort&&Module.onAbort(e),err(e="Aborted("+e+")"),ABORT=!0,EXITSTATUS=1,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}var wasmBinaryFile,tempDouble,tempI64,dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(e){return e.startsWith(dataURIPrefix)}function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(e){return wasmBinary||!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER||"function"!=typeof fetch?Promise.resolve().then(()=>getBinarySync(e)):fetch(e,{credentials:"same-origin"}).then(async t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";postMessage({type:"event",id:-3,body:{total:0,loaded:0,tag:"starting",resourcesPath:e}});const r=+t.headers.get("Content-Length"),n=t.body.getReader();let o=0,a=Date.now();const s=[];for(;;){const{done:t,value:i}=await n.read();if(t)break;if(s.push(i),o+=i.length,r){const t=Date.now();a+500getBinarySync(e))}function instantiateArrayBuffer(e,t,r){return getBinaryPromise(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(r,e=>{err(`failed to asynchronously prepare wasm: ${e}`),abort(e)})}function instantiateAsync(e,t,r,n){return instantiateArrayBuffer(t,r,n)}function createWasm(){var e={env:wasmImports,wasi_snapshot_preview1:wasmImports};function t(e,t){return wasmExports=e.exports,wasmMemory=wasmExports.memory,updateMemoryViews(),wasmTable=wasmExports.__indirect_function_table,addOnInit(wasmExports.__wasm_call_ctors),exportWasmSymbols(wasmExports),removeRunDependency("wasm-instantiate"),wasmExports}if(addRunDependency("wasm-instantiate"),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return err(`Module.instantiateWasm callback failed with error: ${e}`),!1}return instantiateAsync(wasmBinary,wasmBinaryFile,e,function(e){t(e.instance)}),{}}isDataURI(wasmBinaryFile="dynamsoft-barcode-reader-bundle-ml-simd.wasm")||(wasmBinaryFile=locateFile(wasmBinaryFile));var ASM_CONSTS={838984:(e,t,r,n)=>{if(void 0===Module||!Module.MountedFiles)return 1;let o=UTF8ToString(e>>>0);o.startsWith("./")&&(o=o.substring(2));const a=Module.MountedFiles.get(o);if(!a)return 2;const s=t>>>0,i=r>>>0,l=n>>>0;if(s+i>a.byteLength)return 3;try{return HEAPU8.set(a.subarray(s,s+i),l),0}catch{return 4}}},callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},asmjsMangle=e=>("__main_argc_argv"==e&&(e="main"),0==e.indexOf("dynCall_")||["stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0"].includes(e)?e:"_"+e),exportWasmSymbols=e=>{for(var t in e){var r=asmjsMangle(t);this[r]=Module[r]=e[t]}};function _CreateDirectoryFetcher(){abort("missing function: CreateDirectoryFetcher")}function _DDN_ConvertElement(){abort("missing function: DDN_ConvertElement")}function _DDN_CreateDDNResult(){abort("missing function: DDN_CreateDDNResult")}function _DDN_CreateDDNResultItem(){abort("missing function: DDN_CreateDDNResultItem")}function _DDN_CreateIntermediateResultUnits(){abort("missing function: DDN_CreateIntermediateResultUnits")}function _DDN_CreateParameters(){abort("missing function: DDN_CreateParameters")}function _DDN_CreateTargetRoiDefConditionFilter(){abort("missing function: DDN_CreateTargetRoiDefConditionFilter")}function _DDN_CreateTaskAlgEntity(){abort("missing function: DDN_CreateTaskAlgEntity")}function _DDN_HasSection(){abort("missing function: DDN_HasSection")}function _DDN_ReadTaskSetting(){abort("missing function: DDN_ReadTaskSetting")}function _DLR_ConvertElement(){abort("missing function: DLR_ConvertElement")}function _DLR_CreateBufferedCharacterItemSet(){abort("missing function: DLR_CreateBufferedCharacterItemSet")}function _DLR_CreateIntermediateResultUnits(){abort("missing function: DLR_CreateIntermediateResultUnits")}function _DLR_CreateParameters(){abort("missing function: DLR_CreateParameters")}function _DLR_CreateRecognizedTextLinesResult(){abort("missing function: DLR_CreateRecognizedTextLinesResult")}function _DLR_CreateTargetRoiDefConditionFilter(){abort("missing function: DLR_CreateTargetRoiDefConditionFilter")}function _DLR_CreateTaskAlgEntity(){abort("missing function: DLR_CreateTaskAlgEntity")}function _DLR_CreateTextLineResultItem(){abort("missing function: DLR_CreateTextLineResultItem")}function _DLR_ReadTaskSetting(){abort("missing function: DLR_ReadTaskSetting")}function _DMImage_GetDIB(){abort("missing function: DMImage_GetDIB")}function _DMImage_GetOrientation(){abort("missing function: DMImage_GetOrientation")}function _DeleteDirectoryFetcher(){abort("missing function: DeleteDirectoryFetcher")}function __ZN19LabelRecognizerWasm10getVersionEv(){abort("missing function: _ZN19LabelRecognizerWasm10getVersionEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi")}function __ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb")}function __ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClassC1Ev(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev")}function __ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE(){abort("missing function: _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE")}function __ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE(){abort("missing function: _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE")}function __ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE")}function __ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE")}function __ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE(){abort("missing function: _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE")}function __ZN22DocumentNormalizerWasm10getVersionEv(){abort("missing function: _ZN22DocumentNormalizerWasm10getVersionEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii")}function __ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE")}function __ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev")}function __ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE")}function __ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE")}function __ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E(){abort("missing function: _ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E")}function __ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E(){abort("missing function: _ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E")}function __ZN9dynamsoft7utility14CUtilityModule10GetVersionEv(){abort("missing function: _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv")}_CreateDirectoryFetcher.stub=!0,_DDN_ConvertElement.stub=!0,_DDN_CreateDDNResult.stub=!0,_DDN_CreateDDNResultItem.stub=!0,_DDN_CreateIntermediateResultUnits.stub=!0,_DDN_CreateParameters.stub=!0,_DDN_CreateTargetRoiDefConditionFilter.stub=!0,_DDN_CreateTaskAlgEntity.stub=!0,_DDN_HasSection.stub=!0,_DDN_ReadTaskSetting.stub=!0,_DLR_ConvertElement.stub=!0,_DLR_CreateBufferedCharacterItemSet.stub=!0,_DLR_CreateIntermediateResultUnits.stub=!0,_DLR_CreateParameters.stub=!0,_DLR_CreateRecognizedTextLinesResult.stub=!0,_DLR_CreateTargetRoiDefConditionFilter.stub=!0,_DLR_CreateTaskAlgEntity.stub=!0,_DLR_CreateTextLineResultItem.stub=!0,_DLR_ReadTaskSetting.stub=!0,_DMImage_GetDIB.stub=!0,_DMImage_GetOrientation.stub=!0,_DeleteDirectoryFetcher.stub=!0,__ZN19LabelRecognizerWasm10getVersionEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev.stub=!0,__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE.stub=!0,__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE.stub=!0,__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE.stub=!0,__ZN22DocumentNormalizerWasm10getVersionEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev.stub=!0,__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE.stub=!0,__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE.stub=!0,__ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E.stub=!0,__ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E.stub=!0,__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv.stub=!0;var UTF8Decoder="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,UTF8ArrayToString=(e,t,r)=>{for(var n=t+r,o=t;e[o]&&!(o>=n);)++o;if(o-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&c)}}else a+=String.fromCharCode((31&s)<<6|i)}else a+=String.fromCharCode(s)}return a},UTF8ToString=(e,t)=>e?UTF8ArrayToString(HEAPU8,e,t):"",___assert_fail=(e,t,r,n)=>{abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[t?UTF8ToString(t):"unknown filename",r,n?UTF8ToString(n):"unknown function"])},exceptionCaught=[],uncaughtExceptionCount=0,___cxa_begin_catch=e=>{var t=new ExceptionInfo(e);return t.get_caught()||(t.set_caught(!0),uncaughtExceptionCount--),t.set_rethrown(!1),exceptionCaught.push(t),___cxa_increment_exception_refcount(t.excPtr),t.get_exception_ptr()},exceptionLast=0,___cxa_end_catch=()=>{_setThrew(0,0);var e=exceptionCaught.pop();___cxa_decrement_exception_refcount(e.excPtr),exceptionLast=0};function ExceptionInfo(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){HEAPU32[this.ptr+4>>2]=e},this.get_type=function(){return HEAPU32[this.ptr+4>>2]},this.set_destructor=function(e){HEAPU32[this.ptr+8>>2]=e},this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,HEAP8[this.ptr+12|0]=e},this.get_caught=function(){return 0!=HEAP8[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,HEAP8[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=HEAP8[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){HEAPU32[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]},this.get_exception_ptr=function(){if(___cxa_is_pointer_type(this.get_type()))return HEAPU32[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var ___resumeException=e=>{throw exceptionLast||(exceptionLast=e),exceptionLast},findMatchingCatch=e=>{var t=exceptionLast;if(!t)return setTempRet0(0),0;var r=new ExceptionInfo(t);r.set_adjusted_ptr(t);var n=r.get_type();if(!n)return setTempRet0(0),t;for(var o in e){var a=e[o];if(0===a||a===n)break;var s=r.ptr+16;if(___cxa_can_catch(a,n,s))return setTempRet0(a),t}return setTempRet0(n),t},___cxa_find_matching_catch_2=()=>findMatchingCatch([]),___cxa_find_matching_catch_3=e=>findMatchingCatch([e]),___cxa_rethrow=()=>{var e=exceptionCaught.pop();e||abort("no exception to throw");var t=e.excPtr;throw e.get_rethrown()||(exceptionCaught.push(e),e.set_rethrown(!0),e.set_caught(!1),uncaughtExceptionCount++),exceptionLast=t},___cxa_rethrow_primary_exception=e=>{if(e){var t=new ExceptionInfo(e);exceptionCaught.push(t),t.set_rethrown(!0),___cxa_rethrow()}},___cxa_throw=(e,t,r)=>{throw new ExceptionInfo(e).init(t,r),uncaughtExceptionCount++,exceptionLast=e},___cxa_uncaught_exceptions=()=>uncaughtExceptionCount,PATH={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=PATH.isAbs(e),r="/"===e.substr(-1);return(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=PATH.splitPath(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=PATH.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return PATH.normalize(e.join("/"))},join2:(e,t)=>PATH.normalize(e+"/"+t)},initRandomFill=()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:FS.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,t=PATH.isAbs(n)}return(t?"/":"")+(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=PATH_FS.resolve(e).substr(1),t=PATH_FS.resolve(t).substr(1);for(var n=r(e.split("/")),o=r(t.split("/")),a=Math.min(n.length,o.length),s=a,i=0;i{for(var t=0,r=0;r=55296&&n<=57343?(t+=4,++r):t+=3}return t},stringToUTF8Array=(e,t,r,n)=>{if(!(n>0))return 0;for(var o=r,a=r+n-1,s=0;s=55296&&i<=57343)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++s);if(i<=127){if(r>=a)break;t[r++]=i}else if(i<=2047){if(r+1>=a)break;t[r++]=192|i>>6,t[r++]=128|63&i}else if(i<=65535){if(r+2>=a)break;t[r++]=224|i>>12,t[r++]=128|i>>6&63,t[r++]=128|63&i}else{if(r+3>=a)break;t[r++]=240|i>>18,t[r++]=128|i>>12&63,t[r++]=128|i>>6&63,t[r++]=128|63&i}}return t[r]=0,r-o};function intArrayFromString(e,t,r){var n=r>0?r:lengthBytesUTF8(e)+1,o=new Array(n),a=stringToUTF8Array(e,o,0,o.length);return t&&(o.length=a),o}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,t){TTY.ttys[e]={input:[],output:[],ops:t},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var t=TTY.ttys[e.node.rdev];if(!t)throw new FS.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,r,n,o){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var a=0,s=0;sFS_stdin_getChar(),put_char(e,t){null===t||10===t?(out(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(out(UTF8ArrayToString(e.output,0)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,r)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(err(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output,0)),e.output=[])}}},zeroMemory=(e,t)=>(HEAPU8.fill(0,e,e+t),e),alignMemory=(e,t)=>Math.ceil(e/t)*t,mmapAlloc=e=>{e=alignMemory(e,65536);var t=_emscripten_builtin_memalign(65536,e);return t?zeroMemory(t,e):0},MEMFS={ops_table:null,mount:e=>MEMFS.createNode(null,"/",16895,0),createNode(e,t,r,n){if(FS.isBlkdev(r)||FS.isFIFO(r))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var o=FS.createNode(e,t,r,n);return FS.isDir(o.mode)?(o.node_ops=MEMFS.ops_table.dir.node,o.stream_ops=MEMFS.ops_table.dir.stream,o.contents={}):FS.isFile(o.mode)?(o.node_ops=MEMFS.ops_table.file.node,o.stream_ops=MEMFS.ops_table.file.stream,o.usedBytes=0,o.contents=null):FS.isLink(o.mode)?(o.node_ops=MEMFS.ops_table.link.node,o.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(o.mode)&&(o.node_ops=MEMFS.ops_table.chrdev.node,o.stream_ops=MEMFS.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var n=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=FS.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,FS.isDir(e.mode)?t.size=4096:FS.isFile(e.mode)?t.size=e.usedBytes:FS.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&MEMFS.resizeFileStorage(e,t.size)},lookup(e,t){throw FS.genericErrors[44]},mknod:(e,t,r,n)=>MEMFS.createNode(e,t,r,n),rename(e,t,r){if(FS.isDir(e.mode)){var n;try{n=FS.lookupNode(t,r)}catch(e){}if(n)for(var o in n.contents)throw new FS.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=FS.lookupNode(e,t);for(var n in r.contents)throw new FS.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var n=MEMFS.createNode(e,t,41471,0);return n.link=r,n},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-o,n);if(s>8&&a.subarray)t.set(a.subarray(o,o+s),r);else for(var i=0;i0||r+t(MEMFS.stream_ops.write(e,t,0,n,r,!1),0)}},asyncLoad=(e,t,r,n)=>{var o=n?"":getUniqueRunDependency(`al ${e}`);readAsync(e,r=>{assert(r,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(r)),o&&removeRunDependency(o)},t=>{if(!r)throw`Loading data file "${e}" failed.`;r()}),o&&addRunDependency(o)},FS_createDataFile=(e,t,r,n,o,a)=>FS.createDataFile(e,t,r,n,o,a),preloadPlugins=Module.preloadPlugins||[],FS_handledByPreloadPlugin=(e,t,r,n)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return preloadPlugins.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,r,n),o=!0)}),o},FS_createPreloadedFile=(e,t,r,n,o,a,s,i,l,c)=>{var u=t?PATH_FS.resolve(PATH.join2(e,t)):e,m=getUniqueRunDependency(`cp ${u}`);function d(r){function d(r){c&&c(),i||FS_createDataFile(e,t,r,n,o,l),a&&a(),removeRunDependency(m)}FS_handledByPreloadPlugin(r,u,d,()=>{s&&s(),removeRunDependency(m)})||d(r)}addRunDependency(m),"string"==typeof r?asyncLoad(r,e=>d(e),s):d(r)},FS_modeStringToFlags=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t},FS_getMode=(e,t)=>{var r=0;return e&&(r|=365),t&&(r|=146),r},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(!(e=PATH_FS.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new FS.ErrnoError(32);for(var r=e.split("/").filter(e=>!!e),n=FS.root,o="/",a=0;a40)throw new FS.ErrnoError(32)}}return{path:o,node:n}},getPath(e){for(var t;;){if(FS.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?`${r}/${t}`:r+t:r}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var r=0,n=0;n>>0)%FS.nameTable.length},hashAddNode(e){var t=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[t],FS.nameTable[t]=e},hashRemoveNode(e){var t=FS.hashName(e.parent.id,e.name);if(FS.nameTable[t]===e)FS.nameTable[t]=e.name_next;else for(var r=FS.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode(e,t){var r=FS.mayLookup(e);if(r)throw new FS.ErrnoError(r,e);for(var n=FS.hashName(e.id,t),o=FS.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return FS.lookup(e,t)},createNode(e,t,r,n){var o=new FS.FSNode(e,t,r,n);return FS.hashAddNode(o),o},destroyNode(e){FS.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>FS.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){var t=FS.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{FS.lookupNode(e,t);return 20}catch(e){}return FS.nodePermissions(e,"wx")},mayDelete(e,t,r){var n;try{n=FS.lookupNode(e,t)}catch(e){return e.errno}var o=FS.nodePermissions(e,"wx");if(o)return o;if(r){if(!FS.isDir(n.mode))return 54;if(FS.isRoot(n)||FS.getPath(n)===FS.cwd())return 10}else if(FS.isDir(n.mode))return 31;return 0},mayOpen:(e,t)=>e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&("r"!==FS.flagsToPermissionString(t)||512&t)?31:FS.nodePermissions(e,FS.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var t=FS.getStream(e);if(!t)throw new FS.ErrnoError(8);return t},getStream:e=>FS.streams[e],createStream:(e,t=-1)=>(FS.FSStream||(FS.FSStream=function(){this.shared={}},FS.FSStream.prototype={},Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new FS.FSStream,e),-1==t&&(t=FS.nextfd()),e.fd=t,FS.streams[t]=e,e),closeStream(e){FS.streams[e]=null},chrdev_stream_ops:{open(e){var t=FS.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){FS.devices[e]={stream_ops:t}},getDevice:e=>FS.devices[e],getMounts(e){for(var t=[],r=[e];r.length;){var n=r.pop();t.push(n),r.push.apply(r,n.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var r=FS.getMounts(FS.root.mount),n=0;function o(e){return FS.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=r.length&&o(null)}r.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,r){var n,o="/"===r,a=!r;if(o&&FS.root)throw new FS.ErrnoError(10);if(!o&&!a){var s=FS.lookupPath(r,{follow_mount:!1});if(r=s.path,n=s.node,FS.isMountpoint(n))throw new FS.ErrnoError(10);if(!FS.isDir(n.mode))throw new FS.ErrnoError(54)}var i={type:e,opts:t,mountpoint:r,mounts:[]},l=e.mount(i);return l.mount=i,i.root=l,o?FS.root=l:n&&(n.mounted=i,n.mount&&n.mount.mounts.push(i)),l},unmount(e){var t=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(t.node))throw new FS.ErrnoError(28);var r=t.node,n=r.mounted,o=FS.getMounts(n);Object.keys(FS.nameTable).forEach(e=>{for(var t=FS.nameTable[e];t;){var r=t.name_next;o.includes(t.mount)&&FS.destroyNode(t),t=r}}),r.mounted=null;var a=r.mount.mounts.indexOf(n);r.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,r){var n=FS.lookupPath(e,{parent:!0}).node,o=PATH.basename(e);if(!o||"."===o||".."===o)throw new FS.ErrnoError(28);var a=FS.mayCreate(n,o);if(a)throw new FS.ErrnoError(a);if(!n.node_ops.mknod)throw new FS.ErrnoError(63);return n.node_ops.mknod(n,o,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,FS.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,FS.mknod(e,t,0)),mkdirTree(e,t){for(var r=e.split("/"),n="",o=0;o(void 0===r&&(r=t,t=438),t|=8192,FS.mknod(e,t,r)),symlink(e,t){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var r=FS.lookupPath(t,{parent:!0}).node;if(!r)throw new FS.ErrnoError(44);var n=PATH.basename(t),o=FS.mayCreate(r,n);if(o)throw new FS.ErrnoError(o);if(!r.node_ops.symlink)throw new FS.ErrnoError(63);return r.node_ops.symlink(r,n,e)},rename(e,t){var r,n,o=PATH.dirname(e),a=PATH.dirname(t),s=PATH.basename(e),i=PATH.basename(t);if(r=FS.lookupPath(e,{parent:!0}).node,n=FS.lookupPath(t,{parent:!0}).node,!r||!n)throw new FS.ErrnoError(44);if(r.mount!==n.mount)throw new FS.ErrnoError(75);var l,c=FS.lookupNode(r,s),u=PATH_FS.relative(e,a);if("."!==u.charAt(0))throw new FS.ErrnoError(28);if("."!==(u=PATH_FS.relative(t,o)).charAt(0))throw new FS.ErrnoError(55);try{l=FS.lookupNode(n,i)}catch(e){}if(c!==l){var m=FS.isDir(c.mode),d=FS.mayDelete(r,s,m);if(d)throw new FS.ErrnoError(d);if(d=l?FS.mayDelete(n,i,m):FS.mayCreate(n,i))throw new FS.ErrnoError(d);if(!r.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(c)||l&&FS.isMountpoint(l))throw new FS.ErrnoError(10);if(n!==r&&(d=FS.nodePermissions(r,"w")))throw new FS.ErrnoError(d);FS.hashRemoveNode(c);try{r.node_ops.rename(c,n,i)}catch(e){throw e}finally{FS.hashAddNode(c)}}},rmdir(e){var t=FS.lookupPath(e,{parent:!0}).node,r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!0);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.rmdir(t,r),FS.destroyNode(n)},readdir(e){var t=FS.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new FS.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=FS.lookupPath(e,{parent:!0}).node;if(!t)throw new FS.ErrnoError(44);var r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!1);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.unlink(t,r),FS.destroyNode(n)},readlink(e){var t=FS.lookupPath(e).node;if(!t)throw new FS.ErrnoError(44);if(!t.node_ops.readlink)throw new FS.ErrnoError(28);return PATH_FS.resolve(FS.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var r=FS.lookupPath(e,{follow:!t}).node;if(!r)throw new FS.ErrnoError(44);if(!r.node_ops.getattr)throw new FS.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>FS.stat(e,!0),chmod(e,t,r){var n;"string"==typeof e?n=FS.lookupPath(e,{follow:!r}).node:n=e;if(!n.node_ops.setattr)throw new FS.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&t|-4096&n.mode,timestamp:Date.now()})},lchmod(e,t){FS.chmod(e,t,!0)},fchmod(e,t){var r=FS.getStreamChecked(e);FS.chmod(r.node,t)},chown(e,t,r,n){var o;"string"==typeof e?o=FS.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new FS.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,r){FS.chown(e,t,r,!0)},fchown(e,t,r){var n=FS.getStreamChecked(e);FS.chown(n.node,t,r)},truncate(e,t){if(t<0)throw new FS.ErrnoError(28);var r;"string"==typeof e?r=FS.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(r.mode))throw new FS.ErrnoError(31);if(!FS.isFile(r.mode))throw new FS.ErrnoError(28);var n=FS.nodePermissions(r,"w");if(n)throw new FS.ErrnoError(n);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate(e,t){var r=FS.getStreamChecked(e);if(!(2097155&r.flags))throw new FS.ErrnoError(28);FS.truncate(r.node,t)},utime(e,t,r){var n=FS.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(t,r)})},open(e,t,r){if(""===e)throw new FS.ErrnoError(44);var n;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?FS_modeStringToFlags(t):t)?4095&r|32768:0,"object"==typeof e)n=e;else{e=PATH.normalize(e);try{n=FS.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(n){if(128&t)throw new FS.ErrnoError(20)}else n=FS.mknod(e,r,0),o=!0;if(!n)throw new FS.ErrnoError(44);if(FS.isChrdev(n.mode)&&(t&=-513),65536&t&&!FS.isDir(n.mode))throw new FS.ErrnoError(54);if(!o){var a=FS.mayOpen(n,t);if(a)throw new FS.ErrnoError(a)}512&t&&!o&&FS.truncate(n,0),t&=-131713;var s=FS.createStream({node:n,path:FS.getPath(n),flags:t,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!Module.logReadFiles||1&t||(FS.readFiles||(FS.readFiles={}),e in FS.readFiles||(FS.readFiles[e]=1)),s},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{FS.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read(e,t,r,n,o){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(1==(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var s=e.stream_ops.read(e,t,r,n,o);return a||(e.position+=s),s},write(e,t,r,n,o,a){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&1024&e.flags&&FS.llseek(e,0,2);var s=void 0!==o;if(s){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var i=e.stream_ops.write(e,t,r,n,o,a);return s||(e.position+=i),i},allocate(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(t<0||r<=0)throw new FS.ErrnoError(28);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap(e,t,r,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new FS.ErrnoError(2);if(1==(2097155&e.flags))throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);return e.stream_ops.mmap(e,t,r,n,o)},msync:(e,t,r,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,n,o):0,munmap:e=>0,ioctl(e,t,r){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var r,n=FS.open(e,t.flags),o=FS.stat(e).size,a=new Uint8Array(o);return FS.read(n,a,0,o,0),"utf8"===t.encoding?r=UTF8ArrayToString(a,0):"binary"===t.encoding&&(r=a),FS.close(n),r},writeFile(e,t,r={}){r.flags=r.flags||577;var n=FS.open(e,r.flags,r.mode);if("string"==typeof t){var o=new Uint8Array(lengthBytesUTF8(t)+1),a=stringToUTF8Array(t,o,0,o.length);FS.write(n,o,0,a,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");FS.write(n,t,0,t.byteLength,void 0,r.canOwn)}FS.close(n)},cwd:()=>FS.currentPath,chdir(e){var t=FS.lookupPath(e,{follow:!0});if(null===t.node)throw new FS.ErrnoError(44);if(!FS.isDir(t.node.mode))throw new FS.ErrnoError(54);var r=FS.nodePermissions(t.node,"x");if(r)throw new FS.ErrnoError(r);FS.currentPath=t.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(e,t,r,n,o)=>n}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=randomFill(e).byteLength),e[--t]);FS.createDevice("/dev","random",r),FS.createDevice("/dev","urandom",r),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var t=FS.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var r=+t,n=FS.getStreamChecked(r),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(){Module.stdin?FS.createDevice("/dev","stdin",Module.stdin):FS.symlink("/dev/tty","/dev/stdin"),Module.stdout?FS.createDevice("/dev","stdout",null,Module.stdout):FS.symlink("/dev/tty","/dev/stdout"),Module.stderr?FS.createDevice("/dev","stderr",null,Module.stderr):FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},ensureErrnoError(){FS.ErrnoError||(FS.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},FS.ErrnoError.prototype=new Error,FS.ErrnoError.prototype.constructor=FS.ErrnoError,[44].forEach(e=>{FS.genericErrors[e]=new FS.ErrnoError(e),FS.genericErrors[e].stack=""}))},staticInit(){FS.ensureErrnoError(),FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS:MEMFS}},init(e,t,r){FS.init.initialized=!0,FS.ensureErrnoError(),Module.stdin=e||Module.stdin,Module.stdout=t||Module.stdout,Module.stderr=r||Module.stderr,FS.createStandardStreams()},quit(){FS.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,n=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,s=1048576;o||(s=n);var i=this;i.setDataGetter(e=>{var t=e*s,o=(e+1)*s-1;if(o=Math.min(o,n-1),void 0===i.chunks[e]&&(i.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),n!==s&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):intArrayFromString(o.responseText||"",!0)})(t,o)),void 0===i.chunks[e])throw new Error("doXHR failed!");return i.chunks[e]}),!a&&n||(s=n=1,n=this.getter(0).length,s=n,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new a;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var i={isDevice:!1,contents:s}}else i={isDevice:!1,url:r};var l=FS.createFile(e,t,i,n,o);i.contents?l.contents=i.contents:i.url&&(l.contents=null,l.url=i.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,r,n,o){var a=e.node.contents;if(o>=a.length)return 0;var s=Math.min(a.length-o,n);if(a.slice)for(var i=0;i{var t=l.stream_ops[e];c[e]=function(){return FS.forceLoadFile(l),t.apply(null,arguments)}}),c.read=(e,t,r,n,o)=>(FS.forceLoadFile(l),u(e,t,r,n,o)),c.mmap=(e,t,r,n,o)=>{FS.forceLoadFile(l);var a=mmapAlloc(t);if(!a)throw new FS.ErrnoError(48);return u(e,HEAP8,a,t,r),{ptr:a,allocated:!0}},l.stream_ops=c,l}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,t,r){if(PATH.isAbs(t))return t;var n;-100===e?n=FS.cwd():n=SYSCALLS.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new FS.ErrnoError(44);return n}return PATH.join2(n,t)},doStat(e,t,r){try{var n=e(t)}catch(e){if(e&&e.node&&PATH.normalize(t)!==PATH.normalize(FS.getPath(e.node)))return-54;throw e}HEAP32[r>>2]=n.dev,HEAP32[r+4>>2]=n.mode,HEAPU32[r+8>>2]=n.nlink,HEAP32[r+12>>2]=n.uid,HEAP32[r+16>>2]=n.gid,HEAP32[r+20>>2]=n.rdev,tempI64=[n.size>>>0,(tempDouble=n.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+24>>2]=tempI64[0],HEAP32[r+28>>2]=tempI64[1],HEAP32[r+32>>2]=4096,HEAP32[r+36>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),s=n.ctime.getTime();return tempI64=[Math.floor(o/1e3)>>>0,(tempDouble=Math.floor(o/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+40>>2]=tempI64[0],HEAP32[r+44>>2]=tempI64[1],HEAPU32[r+48>>2]=o%1e3*1e3,tempI64=[Math.floor(a/1e3)>>>0,(tempDouble=Math.floor(a/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+56>>2]=tempI64[0],HEAP32[r+60>>2]=tempI64[1],HEAPU32[r+64>>2]=a%1e3*1e3,tempI64=[Math.floor(s/1e3)>>>0,(tempDouble=Math.floor(s/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+72>>2]=tempI64[0],HEAP32[r+76>>2]=tempI64[1],HEAPU32[r+80>>2]=s%1e3*1e3,tempI64=[n.ino>>>0,(tempDouble=n.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+88>>2]=tempI64[0],HEAP32[r+92>>2]=tempI64[1],0},doMsync(e,t,r,n,o){if(!FS.isFile(t.node.mode))throw new FS.ErrnoError(43);if(2&n)return 0;var a=HEAPU8.slice(e,e+r);FS.msync(t,a,o,r,n)},varargs:void 0,get(){var e=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},getp:()=>SYSCALLS.get(),getStr:e=>UTF8ToString(e),getStreamFromFD:e=>FS.getStreamChecked(e)};function ___syscall__newselect(e,t,r,n,o){try{for(var a=0,s=t?HEAP32[t>>2]:0,i=t?HEAP32[t+4>>2]:0,l=r?HEAP32[r>>2]:0,c=r?HEAP32[r+4>>2]:0,u=n?HEAP32[n>>2]:0,m=n?HEAP32[n+4>>2]:0,d=0,_=0,f=0,p=0,g=0,S=0,E=(t?HEAP32[t>>2]:0)|(r?HEAP32[r>>2]:0)|(n?HEAP32[n>>2]:0),h=(t?HEAP32[t+4>>2]:0)|(r?HEAP32[r+4>>2]:0)|(n?HEAP32[n+4>>2]:0),v=function(e,t,r,n){return e<32?t&n:r&n},F=0;F>2]:0)+(t?HEAP32[o+8>>2]:0)/1e6);D=w.stream_ops.poll(w,b)}1&D&&v(F,s,i,y)&&(F<32?d|=y:_|=y,a++),4&D&&v(F,l,c,y)&&(F<32?f|=y:p|=y,a++),2&D&&v(F,u,m,y)&&(F<32?g|=y:S|=y,a++)}}return t&&(HEAP32[t>>2]=d,HEAP32[t+4>>2]=_),r&&(HEAP32[r>>2]=f,HEAP32[r+4>>2]=p),n&&(HEAP32[n>>2]=g,HEAP32[n+4>>2]=S),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var SOCKFS={mount:e=>(Module.websocket=Module.websocket&&"object"==typeof Module.websocket?Module.websocket:{},Module.websocket._callbacks={},Module.websocket.on=function(e,t){return"function"==typeof t&&(this._callbacks[e]=t),this},Module.websocket.emit=function(e,t){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,t)},FS.createNode(null,"/",16895,0)),createSocket(e,t,r){if(1==(t&=-526337)&&r&&6!=r)throw new FS.ErrnoError(66);var n={family:e,type:t,protocol:r,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},o=SOCKFS.nextname(),a=FS.createNode(SOCKFS.root,o,49152,0);a.sock=n;var s=FS.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return n.stream=s,n},getSocket(e){var t=FS.getStream(e);return t&&FS.isSocket(t.node.mode)?t.node.sock:null},stream_ops:{poll(e){var t=e.node.sock;return t.sock_ops.poll(t)},ioctl(e,t,r){var n=e.node.sock;return n.sock_ops.ioctl(n,t,r)},read(e,t,r,n,o){var a=e.node.sock,s=a.sock_ops.recvmsg(a,n);return s?(t.set(s.buffer,r),s.buffer.length):0},write(e,t,r,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,t,r,n)},close(e){var t=e.node.sock;t.sock_ops.close(t)}},nextname:()=>(SOCKFS.nextname.current||(SOCKFS.nextname.current=0),"socket["+SOCKFS.nextname.current+++"]"),websocket_sock_ops:{createPeer(e,t,r){var n;if("object"==typeof t&&(n=t,t=null,r=null),n)if(n._socket)t=n._socket.remoteAddress,r=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");t=o[1],r=parseInt(o[2],10)}else try{var a=Module.websocket&&"object"==typeof Module.websocket,s="ws:#".replace("#","//");if(a&&"string"==typeof Module.websocket.url&&(s=Module.websocket.url),"ws://"===s||"wss://"===s){var i=t.split("/");s=s+i[0]+":"+r+"/"+i.slice(1).join("/")}var l="binary";a&&"string"==typeof Module.websocket.subprotocol&&(l=Module.websocket.subprotocol);var c=void 0;"null"!==l&&(c=l=l.replace(/^ +| +$/g,"").split(/ *, */)),a&&null===Module.websocket.subprotocol&&(l="null",c=void 0),(n=new WebSocket(s,c)).binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}var u={addr:t,port:r,socket:n,dgram_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,u),SOCKFS.websocket_sock_ops.handlePeerEvents(e,u),2===e.type&&void 0!==e.sport&&u.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),u},getPeer:(e,t,r)=>e.peers[t+":"+r],addPeer(e,t){e.peers[t.addr+":"+t.port]=t},removePeer(e,t){delete e.peers[t.addr+":"+t.port]},handlePeerEvents(e,t){var r=!0,n=function(){Module.websocket.emit("open",e.stream.fd);try{for(var r=t.dgram_send_queue.shift();r;)t.socket.send(r),r=t.dgram_send_queue.shift()}catch(e){t.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(assert(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=r;if(r=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var a=n[8]<<8|n[9];return SOCKFS.websocket_sock_ops.removePeer(e,t),t.port=a,void SOCKFS.websocket_sock_ops.addPeer(e,t)}e.recv_queue.push({addr:t.addr,port:t.port,data:n}),Module.websocket.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(t.socket.on("open",n),t.socket.on("message",function(e,t){t&&o(new Uint8Array(e).buffer)}),t.socket.on("close",function(){Module.websocket.emit("close",e.stream.fd)}),t.socket.on("error",function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(t.socket.onopen=n,t.socket.onclose=function(){Module.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){o(e.data)},t.socket.onerror=function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(1===e.type&&e.server)return e.pending.length?65:0;var t=0,r=1===e.type?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!r||r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=65),(!r||r&&r.socket.readyState===r.socket.OPEN)&&(t|=4),(r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=16),t},ioctl(e,t,r){if(21531===t){var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),HEAP32[r>>2]=n,0}return 28},close(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var t=Object.keys(e.peers),r=0;r{var t=SOCKFS.getSocket(e);if(!t)throw new FS.ErrnoError(8);return t},setErrNo=e=>(HEAP32[___errno_location()>>2]=e,e),inetNtop4=e=>(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var t="",r=0,n=0,o=0,a=0,s=0,i=0,l=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,u="";for(i=0;i<5;i++)if(0!==l[i]){c=!1;break}if(c){if(u=inetNtop4(l[6]|l[7]<<16),-1===l[5])return t="::ffff:",t+=u;if(0===l[5])return t="::","0.0.0.0"===u&&(u=""),"0.0.0.1"===u&&(u="1"),t+=u}for(r=0;r<8;r++)0===l[r]&&(r-o>1&&(s=0),o=r,s++),s>n&&(a=r-(n=s)+1);for(r=0;r<8;r++)n>1&&0===l[r]&&r>=a&&r{var r,n=HEAP16[e>>1],o=_ntohs(HEAPU16[e+2>>1]);switch(n){case 2:if(16!==t)return{errno:28};r=HEAP32[e+4>>2],r=inetNtop4(r);break;case 10:if(28!==t)return{errno:28};r=[HEAP32[e+8>>2],HEAP32[e+12>>2],HEAP32[e+16>>2],HEAP32[e+20>>2]],r=inetNtop6(r);break;default:return{errno:5}}return{family:n,addr:r,port:o}},inetPton4=e=>{for(var t=e.split("."),r=0;r<4;r++){var n=Number(t[r]);if(isNaN(n))return null;t[r]=n}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var t,r,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jstoi_q(t[t.length-4])+256*jstoi_q(t[t.length-3]),t[t.length-3]=jstoi_q(t[t.length-2])+256*jstoi_q(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),n=0,o=0,r=0;rDNS.address_map.names[e]?DNS.address_map.names[e]:null},getSocketAddress=(e,t,r)=>{if(r&&0===e)return null;var n=readSockaddr(e,t);if(n.errno)throw new FS.ErrnoError(n.errno);return n.addr=DNS.lookup_addr(n.addr)||n.addr,n};function ___syscall_connect(e,t,r,n,o,a){try{var s=getSocketFromFD(e),i=getSocketAddress(t,r);return s.sock_ops.connect(s,i.addr,i.port),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_faccessat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),-8&r)return-28;var o=FS.lookupPath(t,{follow:!0}).node;if(!o)return-44;var a="";return 4&r&&(a+="r"),2&r&&(a+="w"),1&r&&(a+="x"),a&&FS.nodePermissions(o,a)?-2:0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fcntl64(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 0:if((o=SYSCALLS.get())<0)return-28;for(;FS.streams[o];)o++;return FS.createStream(n,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return n.flags;case 4:var o=SYSCALLS.get();return n.flags|=o,0;case 5:o=SYSCALLS.getp();return HEAP16[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return setErrNo(28),-1}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fstat64(e,t){try{var r=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,r.path,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var stringToUTF8=(e,t,r)=>stringToUTF8Array(e,HEAPU8,t,r);function ___syscall_getcwd(e,t){try{if(0===t)return-28;var r=FS.cwd(),n=lengthBytesUTF8(r)+1;return t>>0,(tempDouble=l,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t+a>>2]=tempI64[0],HEAP32[t+a+4>>2]=tempI64[1],tempI64=[(i+1)*o>>>0,(tempDouble=(i+1)*o,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t+a+8>>2]=tempI64[0],HEAP32[t+a+12>>2]=tempI64[1],HEAP16[t+a+16>>1]=280,HEAP8[t+a+18|0]=c,stringToUTF8(u,t+a+19,256),a+=o,i+=1}return FS.llseek(n,i*o,0),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_ioctl(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return n.tty?0:-59;case 21505:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var o=n.tty.ops.ioctl_tcgets(n),a=SYSCALLS.getp();HEAP32[a>>2]=o.c_iflag||0,HEAP32[a+4>>2]=o.c_oflag||0,HEAP32[a+8>>2]=o.c_cflag||0,HEAP32[a+12>>2]=o.c_lflag||0;for(var s=0;s<32;s++)HEAP8[a+s+17|0]=o.c_cc[s]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){a=SYSCALLS.getp();var i=HEAP32[a>>2],l=HEAP32[a+4>>2],c=HEAP32[a+8>>2],u=HEAP32[a+12>>2],m=[];for(s=0;s<32;s++)m.push(HEAP8[a+s+17|0]);return n.tty.ops.ioctl_tcsets(n.tty,t,{c_iflag:i,c_oflag:l,c_cflag:c,c_lflag:u,c_cc:m})}return 0;case 21519:if(!n.tty)return-59;a=SYSCALLS.getp();return HEAP32[a>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:a=SYSCALLS.getp();return FS.ioctl(n,t,a);case 21523:if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var d=n.tty.ops.ioctl_tiocgwinsz(n.tty);a=SYSCALLS.getp();HEAP16[a>>1]=d[0],HEAP16[a+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_lstat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.lstat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_mkdirat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),"/"===(t=PATH.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),FS.mkdir(t,r,0),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_newfstatat(e,t,r,n){try{t=SYSCALLS.getStr(t);var o=256&n,a=4096&n;return n&=-6401,t=SYSCALLS.calculateAt(e,t,a),SYSCALLS.doStat(o?FS.lstat:FS.stat,t,r)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_openat(e,t,r,n){SYSCALLS.varargs=n;try{t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t);var o=n?SYSCALLS.get():0;return FS.open(t,r,o).fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_readlinkat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),n<=0)return-28;var o=FS.readlink(t),a=Math.min(n,lengthBytesUTF8(o)),s=HEAP8[r+a];return stringToUTF8(o,r,n+1),HEAP8[r+a]=s,a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_rmdir(e){try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_socket(e,t,r){try{return SOCKFS.createSocket(e,t,r).stream.fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_stat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_unlinkat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),0===r?FS.unlink(t):512===r?FS.rmdir(t):abort("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var nowIsMonotonic=!0,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic,convertI32PairToI53Checked=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN;function __gmtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getUTCSeconds(),HEAP32[r+4>>2]=o.getUTCMinutes(),HEAP32[r+8>>2]=o.getUTCHours(),HEAP32[r+12>>2]=o.getUTCDate(),HEAP32[r+16>>2]=o.getUTCMonth(),HEAP32[r+20>>2]=o.getUTCFullYear()-1900,HEAP32[r+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),s=(o.getTime()-a)/864e5|0;HEAP32[r+28>>2]=s}var isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>(isLeapYear(e.getFullYear())?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()]+e.getDate()-1;function __localtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getSeconds(),HEAP32[r+4>>2]=o.getMinutes(),HEAP32[r+8>>2]=o.getHours(),HEAP32[r+12>>2]=o.getDate(),HEAP32[r+16>>2]=o.getMonth(),HEAP32[r+20>>2]=o.getFullYear()-1900,HEAP32[r+24>>2]=o.getDay();var a=0|ydayFromDate(o);HEAP32[r+28>>2]=a,HEAP32[r+36>>2]=-60*o.getTimezoneOffset();var s=new Date(o.getFullYear(),0,1),i=new Date(o.getFullYear(),6,1).getTimezoneOffset(),l=s.getTimezoneOffset(),c=0|(i!=l&&o.getTimezoneOffset()==Math.min(l,i));HEAP32[r+32>>2]=c}var __mktime_js=function(e){var t=(()=>{var t=new Date(HEAP32[e+20>>2]+1900,HEAP32[e+16>>2],HEAP32[e+12>>2],HEAP32[e+8>>2],HEAP32[e+4>>2],HEAP32[e>>2],0),r=HEAP32[e+32>>2],n=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),i=Math.min(s,a);if(r<0)HEAP32[e+32>>2]=Number(a!=s&&i==n);else if(r>0!=(i==n)){var l=Math.max(s,a),c=r>0?i:l;t.setTime(t.getTime()+6e4*(c-n))}HEAP32[e+24>>2]=t.getDay();var u=0|ydayFromDate(t);return HEAP32[e+28>>2]=u,HEAP32[e>>2]=t.getSeconds(),HEAP32[e+4>>2]=t.getMinutes(),HEAP32[e+8>>2]=t.getHours(),HEAP32[e+12>>2]=t.getDate(),HEAP32[e+16>>2]=t.getMonth(),HEAP32[e+20>>2]=t.getYear(),t.getTime()/1e3})();return setTempRet0((tempDouble=t,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)),t>>>0};function __mmap_js(e,t,r,n,o,a,s,i){var l=convertI32PairToI53Checked(o,a);try{if(isNaN(l))return 61;var c=SYSCALLS.getStreamFromFD(n),u=FS.mmap(c,e,l,t,r),m=u.ptr;return HEAP32[s>>2]=u.allocated,HEAPU32[i>>2]=m,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function __munmap_js(e,t,r,n,o,a,s){var i=convertI32PairToI53Checked(a,s);try{if(isNaN(i))return 61;var l=SYSCALLS.getStreamFromFD(o);2&r&&SYSCALLS.doMsync(e,l,t,n,i),FS.munmap(l)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var _emscripten_get_now,stringToNewUTF8=e=>{var t=lengthBytesUTF8(e)+1,r=_malloc(t);return r&&stringToUTF8(e,r,t),r},__tzset_js=(e,t,r)=>{var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),s=o.getTimezoneOffset(),i=a.getTimezoneOffset(),l=Math.max(s,i);function c(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}HEAPU32[e>>2]=60*l,HEAP32[t>>2]=Number(s!=i);var u=c(o),m=c(a),d=stringToNewUTF8(u),_=stringToNewUTF8(m);i>2]=d,HEAPU32[r+4>>2]=_):(HEAPU32[r>>2]=_,HEAPU32[r+4>>2]=d)},_abort=()=>{abort("")},readEmAsmArgsArray=[],readEmAsmArgs=(e,t)=>{var r;for(readEmAsmArgsArray.length=0;r=HEAPU8[e++];){var n=105!=r;t+=(n&=112!=r)&&t%8?4:0,readEmAsmArgsArray.push(112==r?HEAPU32[t>>2]:105==r?HEAP32[t>>2]:HEAPF64[t>>3]),t+=n?8:4}return readEmAsmArgsArray},runEmAsmFunction=(e,t,r)=>{var n=readEmAsmArgs(t,r);return ASM_CONSTS[e].apply(null,n)},_emscripten_asm_const_int=(e,t,r)=>runEmAsmFunction(e,t,r),_emscripten_date_now=()=>Date.now(),_emscripten_errn=(e,t)=>err(UTF8ToString(e,t)),getHeapMax=()=>2147483648,_emscripten_get_heap_max=()=>getHeapMax();_emscripten_get_now=()=>performance.now();var reallyNegative=e=>e<0||0===e&&1/e==-1/0,convertI32PairToI53=(e,t)=>(e>>>0)+4294967296*t,convertU32PairToI53=(e,t)=>(e>>>0)+4294967296*(t>>>0),reSign=(e,t)=>{if(e<=0)return e;var r=t<=32?Math.abs(1<=r&&(t<=32||e>r)&&(e=-2*r+e),e},unSign=(e,t)=>e>=0?e:t<=32?2*Math.abs(1<{for(var t=e;HEAPU8[t];)++t;return t-e},formatString=(e,t)=>{var r=e,n=t;function o(e){var t;return n=function(e,t){return"double"!==t&&"i64"!==t||7&e&&(e+=4),e}(n,e),"double"===e?(t=HEAPF64[n>>3],n+=8):"i64"==e?(t=[HEAP32[n>>2],HEAP32[n+4>>2]],n+=8):(e="i32",t=HEAP32[n>>2],n+=4),t}for(var a,s,i,l=[];;){var c=r;if(0===(a=HEAP8[r|0]))break;if(s=HEAP8[r+1|0],37==a){var u=!1,m=!1,d=!1,_=!1,f=!1;e:for(;;){switch(s){case 43:u=!0;break;case 45:m=!0;break;case 35:d=!0;break;case 48:if(_)break e;_=!0;break;case 32:f=!0;break;default:break e}r++,s=HEAP8[r+1|0]}var p=0;if(42==s)p=o("i32"),r++,s=HEAP8[r+1|0];else for(;s>=48&&s<=57;)p=10*p+(s-48),r++,s=HEAP8[r+1|0];var g,S=!1,E=-1;if(46==s){if(E=0,S=!0,r++,42==(s=HEAP8[r+1|0]))E=o("i32"),r++;else for(;;){var h=HEAP8[r+1|0];if(h<48||h>57)break;E=10*E+(h-48),r++}s=HEAP8[r+1|0]}switch(E<0&&(E=6,S=!1),String.fromCharCode(s)){case"h":104==HEAP8[r+2|0]?(r++,g=1):g=2;break;case"l":108==HEAP8[r+2|0]?(r++,g=8):g=4;break;case"L":case"q":case"j":g=8;break;case"z":case"t":case"I":g=4;break;default:g=null}switch(g&&r++,s=HEAP8[r+1|0],String.fromCharCode(s)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":var v=100==s||105==s;if(i=o("i"+8*(g=g||4)),8==g&&(i=117==s?convertU32PairToI53(i[0],i[1]):convertI32PairToI53(i[0],i[1])),g<=4){var F=Math.pow(256,g)-1;i=(v?reSign:unSign)(i&F,8*g)}var y=Math.abs(i),w="";if(100==s||105==s)k=reSign(i,8*g).toString(10);else if(117==s)k=unSign(i,8*g).toString(10),i=Math.abs(i);else if(111==s)k=(d?"0":"")+y.toString(8);else if(120==s||88==s){if(w=d&&0!=i?"0x":"",i<0){i=-i,k=(y-1).toString(16);for(var D=[],b=0;b=0&&(u?w="+"+w:f&&(w=" "+w)),"-"==k.charAt(0)&&(w="-"+w,k=k.substr(1));w.length+k.lengthP&&P>=-4?(s=(103==s?"f":"F").charCodeAt(0),E-=P+1):(s=(103==s?"e":"E").charCodeAt(0),E--),T=Math.min(E,20)}101==s||69==s?(k=i.toExponential(T),/[eE][-+]\d$/.test(k)&&(k=k.slice(0,-1)+"0"+k.slice(-1))):102!=s&&70!=s||(k=i.toFixed(T),0===i&&reallyNegative(i)&&(k="-"+k));var C=k.split("e");if(A&&!d)for(;C[0].length>1&&C[0].includes(".")&&("0"==C[0].slice(-1)||"."==C[0].slice(-1));)C[0]=C[0].slice(0,-1);else for(d&&-1==k.indexOf(".")&&(C[0]+=".");E>T++;)C[0]+="0";k=C[0]+(C.length>1?"e"+C[1]:""),69==s&&(k=k.toUpperCase()),i>=0&&(u?k="+"+k:f&&(k=" "+k))}else k=(i<0?"-":"")+"inf",_=!1;for(;k.length0;)l.push(32);m||l.push(o("i8"));break;case"n":var M=o("i32*");HEAP32[M>>2]=l.length;break;case"%":l.push(a);break;default:for(b=c;b{warnOnce.shown||(warnOnce.shown={}),warnOnce.shown[e]||(warnOnce.shown[e]=1,err(e))};function getCallstack(e){var t=jsStackTrace(),r=t.lastIndexOf("_emscripten_log"),n=t.lastIndexOf("_emscripten_get_callstack"),o=t.indexOf("\n",Math.max(r,n))+1;t=t.slice(o),8&e&&"undefined"==typeof emscripten_source_map&&(warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'),e^=8,e|=16);var a=t.split("\n");t="";var s=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"),i=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"),l=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var c in a){var u=a[c],m="",d="",_=0,f=0,p=l.exec(u);if(p&&5==p.length)m=p[1],d=p[2],_=p[3],f=p[4];else{if((p=s.exec(u))||(p=i.exec(u)),!(p&&p.length>=4)){t+=u+"\n";continue}m=p[1],d=p[2],_=p[3],f=0|p[4]}var g=!1;if(8&e){var S=emscripten_source_map.originalPositionFor({line:_,column:f});(g=S&&S.source)&&(64&e&&(S.source=S.source.substring(S.source.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=` at ${m} (${S.source}:${S.line}:${S.column})\n`)}(16&e||!g)&&(64&e&&(d=d.substring(d.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=(g?` = ${m}`:` at ${m}`)+` (${d}:${_}:${f})\n`)}return t=t.replace(/\s+$/,"")}var emscriptenLog=(e,t)=>{24&e&&(t=t.replace(/\s+$/,""),t+=(t.length>0?"\n":"")+getCallstack(e)),1&e?4&e||2&e?err(t):out(t):6&e?err(t):out(t)},_emscripten_log=(e,t,r)=>{var n=formatString(t,r),o=UTF8ArrayToString(n,0);emscriptenLog(e,o)},growMemory=e=>{var t=(e-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch(e){}},_emscripten_resize_heap=e=>{var t=HEAPU8.length;e>>>=0;var r=getHeapMax();if(e>r)return!1;for(var n=(e,t)=>e+(t-e%t)%t,o=1;o<=4;o*=2){var a=t*(1+.2/o);a=Math.min(a,e+100663296);var s=Math.min(r,n(Math.max(e,a),65536));if(growMemory(s))return!0}return!1},ENV={},getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(var t in ENV)void 0===ENV[t]?delete e[t]:e[t]=ENV[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToAscii=(e,t)=>{for(var r=0;r{var r=0;return getEnvStrings().forEach((n,o)=>{var a=t+r;HEAPU32[e+4*o>>2]=a,stringToAscii(n,a),r+=n.length+1}),0},_environ_sizes_get=(e,t)=>{var r=getEnvStrings();HEAPU32[e>>2]=r.length;var n=0;return r.forEach(e=>n+=e.length+1),HEAPU32[t>>2]=n,0};function _fd_close(e){try{var t=SYSCALLS.getStreamFromFD(e);return FS.close(t),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doReadv=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.read(e,HEAP8,s,i,n);if(l<0)return-1;if(o+=l,l>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}function _fd_seek(e,t,r,n,o){var a=convertI32PairToI53Checked(t,r);try{if(isNaN(a))return 61;var s=SYSCALLS.getStreamFromFD(e);return FS.llseek(s,a,n),tempI64=[s.position>>>0,(tempDouble=s.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[o>>2]=tempI64[0],HEAP32[o+4>>2]=tempI64[1],s.getdents&&0===a&&0===n&&(s.getdents=null),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doWritev=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.write(e,HEAP8,s,i,n);if(l<0)return-1;o+=l,void 0!==n&&(n+=l)}return o};function _fd_write(e,t,r,n){try{var o=SYSCALLS.getStreamFromFD(e),a=doWritev(o,t,r);return HEAPU32[n>>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var wasmTable,functionsInTableMap,arraySum=(e,t)=>{for(var r=0,n=0;n<=t;r+=e[n++]);return r},MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31],MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31],addDays=(e,t)=>{for(var r=new Date(e.getTime());t>0;){var n=isLeapYear(r.getFullYear()),o=r.getMonth(),a=(n?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[o];if(!(t>a-r.getDate()))return r.setDate(r.getDate()+t),r;t-=a-r.getDate()+1,r.setDate(1),o<11?r.setMonth(o+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r},writeArrayToMemory=(e,t)=>{HEAP8.set(e,t)},_strftime=(e,t,r,n)=>{var o=HEAPU32[n+40>>2],a={tm_sec:HEAP32[n>>2],tm_min:HEAP32[n+4>>2],tm_hour:HEAP32[n+8>>2],tm_mday:HEAP32[n+12>>2],tm_mon:HEAP32[n+16>>2],tm_year:HEAP32[n+20>>2],tm_wday:HEAP32[n+24>>2],tm_yday:HEAP32[n+28>>2],tm_isdst:HEAP32[n+32>>2],tm_gmtoff:HEAP32[n+36>>2],tm_zone:o?UTF8ToString(o):""},s=UTF8ToString(r),i={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in i)s=s.replace(new RegExp(l,"g"),i[l]);var c=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"];function m(e,t,r){for(var n="number"==typeof e?e.toString():e||"";n.length0?1:0}var n;return 0===(n=r(e.getFullYear()-t.getFullYear()))&&0===(n=r(e.getMonth()-t.getMonth()))&&(n=r(e.getDate()-t.getDate())),n}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function p(e){var t=addDays(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),n=new Date(t.getFullYear()+1,0,4),o=f(r),a=f(n);return _(o,t)<=0?_(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var g={"%a":e=>c[e.tm_wday].substring(0,3),"%A":e=>c[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>d((e.tm_year+1900)/100|0,2),"%d":e=>d(e.tm_mday,2),"%e":e=>m(e.tm_mday,2," "),"%g":e=>p(e).toString().substring(2),"%G":e=>p(e),"%H":e=>d(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":e=>d(e.tm_mday+arraySum(isLeapYear(e.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,e.tm_mon-1),3),"%m":e=>d(e.tm_mon+1,2),"%M":e=>d(e.tm_min,2),"%n":()=>"\n","%p":e=>e.tm_hour>=0&&e.tm_hour<12?"AM":"PM","%S":e=>d(e.tm_sec,2),"%t":()=>"\t","%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&isLeapYear(e.tm_year)||(t=1)}}else{t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(4==n||5==n&&isLeapYear(e.tm_year%400-1))&&t++}return d(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>"%"};for(var l in s=s.replace(/%%/g,"\0\0"),g)s.includes(l)&&(s=s.replace(new RegExp(l,"g"),g[l](a)));var S=intArrayFromString(s=s.replace(/\0\0/g,"%"),!1);return S.length>t?0:(writeArrayToMemory(S,e),S.length-1)},_strftime_l=(e,t,r,n,o)=>_strftime(e,t,r,n),getWasmTableEntry=e=>wasmTable.get(e),uleb128Encode=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var t={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"},r={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},n=1;n{var r=e.slice(0,1),n=e.slice(1),o={i:127,p:127,j:126,f:125,d:124};t.push(96),uleb128Encode(n.length,t);for(var a=0;a{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function(sigToWasmTypes(t),e);var r=[1];generateFuncType(t,r);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(r.length,n),n.push.apply(n,r),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var o=new WebAssembly.Module(new Uint8Array(n));return new WebAssembly.Instance(o,{e:{f:e}}).exports.f},updateTableMap=(e,t)=>{if(functionsInTableMap)for(var r=e;r(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1},setWasmTableEntry=(e,t)=>wasmTable.set(e,t),addFunction=(e,t)=>{var r=getFunctionAddress(e);if(r)return r;var n=getEmptyTableSlot();try{setWasmTableEntry(n,e)}catch(r){if(!(r instanceof TypeError))throw r;var o=convertJsFunctionToWasm(e,t);setWasmTableEntry(n,o)}return functionsInTableMap.set(e,n),n},stringToUTF8OnStack=e=>{var t=lengthBytesUTF8(e)+1,r=stackAlloc(t);return stringToUTF8(e,r,t),r},FSNode=function(e,t,r,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=FS.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n},readMode=365,writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(e){e?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(e){e?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}}),FS.FSNode=FSNode,FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit();var calledRun,wasmImports={CreateDirectoryFetcher:_CreateDirectoryFetcher,DDN_ConvertElement:_DDN_ConvertElement,DDN_CreateDDNResult:_DDN_CreateDDNResult,DDN_CreateDDNResultItem:_DDN_CreateDDNResultItem,DDN_CreateIntermediateResultUnits:_DDN_CreateIntermediateResultUnits,DDN_CreateParameters:_DDN_CreateParameters,DDN_CreateTargetRoiDefConditionFilter:_DDN_CreateTargetRoiDefConditionFilter,DDN_CreateTaskAlgEntity:_DDN_CreateTaskAlgEntity,DDN_HasSection:_DDN_HasSection,DDN_ReadTaskSetting:_DDN_ReadTaskSetting,DLR_ConvertElement:_DLR_ConvertElement,DLR_CreateBufferedCharacterItemSet:_DLR_CreateBufferedCharacterItemSet,DLR_CreateIntermediateResultUnits:_DLR_CreateIntermediateResultUnits,DLR_CreateParameters:_DLR_CreateParameters,DLR_CreateRecognizedTextLinesResult:_DLR_CreateRecognizedTextLinesResult,DLR_CreateTargetRoiDefConditionFilter:_DLR_CreateTargetRoiDefConditionFilter,DLR_CreateTaskAlgEntity:_DLR_CreateTaskAlgEntity,DLR_CreateTextLineResultItem:_DLR_CreateTextLineResultItem,DLR_ReadTaskSetting:_DLR_ReadTaskSetting,DMImage_GetDIB:_DMImage_GetDIB,DMImage_GetOrientation:_DMImage_GetOrientation,DeleteDirectoryFetcher:_DeleteDirectoryFetcher,_ZN19LabelRecognizerWasm10getVersionEv:__ZN19LabelRecognizerWasm10getVersionEv,_ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv:__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv,_ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv:__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv,_ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi:__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi,_ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb:__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb,_ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb:__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb,_ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb:__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb,_ZN19LabelRecognizerWasm12DlrWasmClassC1Ev:__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev,_ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE:__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE,_ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE:__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE,_ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE:__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE,_ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE:__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE,_ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE:__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE,_ZN22DocumentNormalizerWasm10getVersionEv:__ZN22DocumentNormalizerWasm10getVersionEv,_ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv:__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv,_ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi:__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi,_ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii:__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii,_ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE,_ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev:__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev,_ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE:__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE,_ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE:__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE,_ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E:__ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E,_ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E:__ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E,_ZN9dynamsoft7utility14CUtilityModule10GetVersionEv:__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv,__assert_fail:___assert_fail,__cxa_begin_catch:___cxa_begin_catch,__cxa_end_catch:___cxa_end_catch,__cxa_find_matching_catch_2:___cxa_find_matching_catch_2,__cxa_find_matching_catch_3:___cxa_find_matching_catch_3,__cxa_rethrow:___cxa_rethrow,__cxa_rethrow_primary_exception:___cxa_rethrow_primary_exception,__cxa_throw:___cxa_throw,__cxa_uncaught_exceptions:___cxa_uncaught_exceptions,__resumeException:___resumeException,__syscall__newselect:___syscall__newselect,__syscall_connect:___syscall_connect,__syscall_faccessat:___syscall_faccessat,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_readlinkat:___syscall_readlinkat,__syscall_rmdir:___syscall_rmdir,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_unlinkat:___syscall_unlinkat,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_mktime_js:__mktime_js,_mmap_js:__mmap_js,_munmap_js:__munmap_js,_tzset_js:__tzset_js,abort:_abort,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_date_now:_emscripten_date_now,emscripten_errn:_emscripten_errn,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_log:_emscripten_log,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,invoke_diii:invoke_diii,invoke_fiii:invoke_fiii,invoke_i:invoke_i,invoke_ii:invoke_ii,invoke_iii:invoke_iii,invoke_iiii:invoke_iiii,invoke_iiiii:invoke_iiiii,invoke_iiiiid:invoke_iiiiid,invoke_iiiiii:invoke_iiiiii,invoke_iiiiiii:invoke_iiiiiii,invoke_iiiiiiii:invoke_iiiiiiii,invoke_iiiiiiiiiiii:invoke_iiiiiiiiiiii,invoke_iiiiij:invoke_iiiiij,invoke_j:invoke_j,invoke_ji:invoke_ji,invoke_jii:invoke_jii,invoke_jiiii:invoke_jiiii,invoke_v:invoke_v,invoke_vi:invoke_vi,invoke_vii:invoke_vii,invoke_viid:invoke_viid,invoke_viii:invoke_viii,invoke_viiii:invoke_viiii,invoke_viiiiiii:invoke_viiiiiii,invoke_viiiiiiiiii:invoke_viiiiiiiiii,invoke_viiiiiiiiiiiiiii:invoke_viiiiiiiiiiiiiii,strftime:_strftime,strftime_l:_strftime_l},wasmExports=createWasm();function invoke_iiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(e,t){var r=stackSave();try{return getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(e,t,r){var n=stackSave();try{return getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(e,t,r){var n=stackSave();try{getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(e,t){var r=stackSave();try{getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(e){var t=stackSave();try{getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(e,t,r,n,o,a,s){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(e,t,r,n,o){var a=stackSave();try{getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiid(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(e,t,r,n,o){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_diii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(e){var t=stackSave();try{return getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,m){var d=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,m)}catch(e){if(stackRestore(d),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u){var m=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u)}catch(e){if(stackRestore(m),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,m,d,_,f,p){var g=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,m,d,_,f,p)}catch(e){if(stackRestore(g),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_j(e){var t=stackSave();try{return dynCall_j(e)}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(e,t){var r=stackSave();try{return dynCall_ji(e,t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(e,t,r){var n=stackSave();try{return dynCall_jii(e,t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiij(e,t,r,n,o,a,s){var i=stackSave();try{return dynCall_iiiiij(e,t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(e,t,r,n,o){var a=stackSave();try{return dynCall_jiiii(e,t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function run(){function e(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT||(initRuntime(),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)]()[UTF8ToString(r)]()),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack((new(self[UTF8ToString(e)]))[UTF8ToString(t)](UTF8ToString(r))),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>{self[UTF8ToString(e)](null,UTF8ToString(t).trim(),UTF8ToString(r),n)},"viiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)][UTF8ToString(r)](UTF8ToString(n))?"":self[UTF8ToString(e)][UTF8ToString(t)]),"iiiii")),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun()))}runDependencies>0||(preRun(),runDependencies>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()))}if(Module.addFunction=addFunction,Module.stringToUTF8OnStack=stringToUTF8OnStack,dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)},Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();run(); \ No newline at end of file diff --git a/dist/dynamsoft-barcode-reader-bundle-ml-simd.wasm b/dist/dynamsoft-barcode-reader-bundle-ml-simd.wasm index 119991a..8b8e199 100644 Binary files a/dist/dynamsoft-barcode-reader-bundle-ml-simd.wasm and b/dist/dynamsoft-barcode-reader-bundle-ml-simd.wasm differ diff --git a/dist/dynamsoft-barcode-reader-bundle-ml.js b/dist/dynamsoft-barcode-reader-bundle-ml.js deleted file mode 100644 index 87c8bfe..0000000 --- a/dist/dynamsoft-barcode-reader-bundle-ml.js +++ /dev/null @@ -1 +0,0 @@ -var read_,readAsync,readBinary,Module=void 0!==Module?Module:{},moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(e,t)=>{throw t},ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!0,ENVIRONMENT_IS_NODE=!1,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:"undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=0!==scriptDirectory.indexOf("blob:")?scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1):"",read_=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),readAsync=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var wasmBinary,out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit),Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,noExitRuntime=Module.noExitRuntime||!0;"object"!=typeof WebAssembly&&abort("no native wasm support detected");var EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,ABORT=!1;function assert(e,t){e||abort(t)}function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e)}var __ATPRERUN__=[],__ATINIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,Module.noFSInit||FS.init.initialized||FS.init(),FS.ignorePermissions=!1,TTY.init(),SOCKFS.root=FS.mount(SOCKFS,{},null),callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module.postRun)for("function"==typeof Module.postRun&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(e){return e}function addRunDependency(e){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}function removeRunDependency(e){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}function abort(e){throw Module.onAbort&&Module.onAbort(e),err(e="Aborted("+e+")"),ABORT=!0,EXITSTATUS=1,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}var wasmBinaryFile,tempDouble,tempI64,dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(e){return e.startsWith(dataURIPrefix)}function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(e){return wasmBinary||!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER||"function"!=typeof fetch?Promise.resolve().then(()=>getBinarySync(e)):fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()}).catch(()=>getBinarySync(e))}function instantiateArrayBuffer(e,t,r){return getBinaryPromise(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(r,e=>{err(`failed to asynchronously prepare wasm: ${e}`),abort(e)})}function instantiateAsync(e,t,r,n){return e||"function"!=typeof WebAssembly.instantiateStreaming||isDataURI(t)||"function"!=typeof fetch?instantiateArrayBuffer(t,r,n):fetch(t,{credentials:"same-origin"}).then(e=>WebAssembly.instantiateStreaming(e,r).then(n,function(e){return err(`wasm streaming compile failed: ${e}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(t,r,n)}))}function createWasm(){var e={env:wasmImports,wasi_snapshot_preview1:wasmImports};function t(e,t){return wasmExports=e.exports,wasmMemory=wasmExports.memory,updateMemoryViews(),wasmTable=wasmExports.__indirect_function_table,addOnInit(wasmExports.__wasm_call_ctors),exportWasmSymbols(wasmExports),removeRunDependency("wasm-instantiate"),wasmExports}if(addRunDependency("wasm-instantiate"),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return err(`Module.instantiateWasm callback failed with error: ${e}`),!1}return instantiateAsync(wasmBinary,wasmBinaryFile,e,function(e){t(e.instance)}),{}}isDataURI(wasmBinaryFile="dynamsoft-barcode-reader-bundle-ml.wasm")||(wasmBinaryFile=locateFile(wasmBinaryFile));var ASM_CONSTS={831048:(e,t,r,n)=>{if(void 0===Module||!Module.MountedFiles)return 1;let o=UTF8ToString(e>>>0);o.startsWith("./")&&(o=o.substring(2));const a=Module.MountedFiles.get(o);if(!a)return 2;const s=t>>>0,i=r>>>0,l=n>>>0;if(s+i>a.byteLength)return 3;try{return HEAPU8.set(a.subarray(s,s+i),l),0}catch{return 4}}},callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},asmjsMangle=e=>("__main_argc_argv"==e&&(e="main"),0==e.indexOf("dynCall_")||["stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0"].includes(e)?e:"_"+e),exportWasmSymbols=e=>{for(var t in e){var r=asmjsMangle(t);this[r]=Module[r]=e[t]}};function _CreateDirectoryFetcher(){abort("missing function: CreateDirectoryFetcher")}function _DDN_ConvertElement(){abort("missing function: DDN_ConvertElement")}function _DDN_CreateDDNResult(){abort("missing function: DDN_CreateDDNResult")}function _DDN_CreateDDNResultItem(){abort("missing function: DDN_CreateDDNResultItem")}function _DDN_CreateIntermediateResultUnits(){abort("missing function: DDN_CreateIntermediateResultUnits")}function _DDN_CreateParameters(){abort("missing function: DDN_CreateParameters")}function _DDN_CreateTargetRoiDefConditionFilter(){abort("missing function: DDN_CreateTargetRoiDefConditionFilter")}function _DDN_CreateTaskAlgEntity(){abort("missing function: DDN_CreateTaskAlgEntity")}function _DDN_HasSection(){abort("missing function: DDN_HasSection")}function _DDN_ReadTaskSetting(){abort("missing function: DDN_ReadTaskSetting")}function _DLR_ConvertElement(){abort("missing function: DLR_ConvertElement")}function _DLR_CreateBufferedCharacterItemSet(){abort("missing function: DLR_CreateBufferedCharacterItemSet")}function _DLR_CreateIntermediateResultUnits(){abort("missing function: DLR_CreateIntermediateResultUnits")}function _DLR_CreateParameters(){abort("missing function: DLR_CreateParameters")}function _DLR_CreateRecognizedTextLinesResult(){abort("missing function: DLR_CreateRecognizedTextLinesResult")}function _DLR_CreateTargetRoiDefConditionFilter(){abort("missing function: DLR_CreateTargetRoiDefConditionFilter")}function _DLR_CreateTaskAlgEntity(){abort("missing function: DLR_CreateTaskAlgEntity")}function _DLR_CreateTextLineResultItem(){abort("missing function: DLR_CreateTextLineResultItem")}function _DLR_ReadTaskSetting(){abort("missing function: DLR_ReadTaskSetting")}function _DMImage_GetDIB(){abort("missing function: DMImage_GetDIB")}function _DMImage_GetOrientation(){abort("missing function: DMImage_GetOrientation")}function _DeleteDirectoryFetcher(){abort("missing function: DeleteDirectoryFetcher")}function __ZN19LabelRecognizerWasm10getVersionEv(){abort("missing function: _ZN19LabelRecognizerWasm10getVersionEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi")}function __ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb")}function __ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClassC1Ev(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev")}function __ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE(){abort("missing function: _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE")}function __ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE(){abort("missing function: _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE")}function __ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE")}function __ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE")}function __ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE(){abort("missing function: _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE")}function __ZN22DocumentNormalizerWasm10getVersionEv(){abort("missing function: _ZN22DocumentNormalizerWasm10getVersionEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii")}function __ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE")}function __ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev")}function __ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE")}function __ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE")}function __ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E(){abort("missing function: _ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E")}function __ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E(){abort("missing function: _ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E")}function __ZN9dynamsoft7utility14CUtilityModule10GetVersionEv(){abort("missing function: _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv")}_CreateDirectoryFetcher.stub=!0,_DDN_ConvertElement.stub=!0,_DDN_CreateDDNResult.stub=!0,_DDN_CreateDDNResultItem.stub=!0,_DDN_CreateIntermediateResultUnits.stub=!0,_DDN_CreateParameters.stub=!0,_DDN_CreateTargetRoiDefConditionFilter.stub=!0,_DDN_CreateTaskAlgEntity.stub=!0,_DDN_HasSection.stub=!0,_DDN_ReadTaskSetting.stub=!0,_DLR_ConvertElement.stub=!0,_DLR_CreateBufferedCharacterItemSet.stub=!0,_DLR_CreateIntermediateResultUnits.stub=!0,_DLR_CreateParameters.stub=!0,_DLR_CreateRecognizedTextLinesResult.stub=!0,_DLR_CreateTargetRoiDefConditionFilter.stub=!0,_DLR_CreateTaskAlgEntity.stub=!0,_DLR_CreateTextLineResultItem.stub=!0,_DLR_ReadTaskSetting.stub=!0,_DMImage_GetDIB.stub=!0,_DMImage_GetOrientation.stub=!0,_DeleteDirectoryFetcher.stub=!0,__ZN19LabelRecognizerWasm10getVersionEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev.stub=!0,__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE.stub=!0,__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE.stub=!0,__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE.stub=!0,__ZN22DocumentNormalizerWasm10getVersionEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev.stub=!0,__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE.stub=!0,__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE.stub=!0,__ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E.stub=!0,__ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E.stub=!0,__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv.stub=!0;var UTF8Decoder="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,UTF8ArrayToString=(e,t,r)=>{for(var n=t+r,o=t;e[o]&&!(o>=n);)++o;if(o-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&c)}}else a+=String.fromCharCode((31&s)<<6|i)}else a+=String.fromCharCode(s)}return a},UTF8ToString=(e,t)=>e?UTF8ArrayToString(HEAPU8,e,t):"",___assert_fail=(e,t,r,n)=>{abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[t?UTF8ToString(t):"unknown filename",r,n?UTF8ToString(n):"unknown function"])},exceptionCaught=[],uncaughtExceptionCount=0,___cxa_begin_catch=e=>{var t=new ExceptionInfo(e);return t.get_caught()||(t.set_caught(!0),uncaughtExceptionCount--),t.set_rethrown(!1),exceptionCaught.push(t),___cxa_increment_exception_refcount(t.excPtr),t.get_exception_ptr()},exceptionLast=0,___cxa_end_catch=()=>{_setThrew(0,0);var e=exceptionCaught.pop();___cxa_decrement_exception_refcount(e.excPtr),exceptionLast=0};function ExceptionInfo(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){HEAPU32[this.ptr+4>>2]=e},this.get_type=function(){return HEAPU32[this.ptr+4>>2]},this.set_destructor=function(e){HEAPU32[this.ptr+8>>2]=e},this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,HEAP8[this.ptr+12|0]=e},this.get_caught=function(){return 0!=HEAP8[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,HEAP8[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=HEAP8[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){HEAPU32[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]},this.get_exception_ptr=function(){if(___cxa_is_pointer_type(this.get_type()))return HEAPU32[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var ___resumeException=e=>{throw exceptionLast||(exceptionLast=e),exceptionLast},findMatchingCatch=e=>{var t=exceptionLast;if(!t)return setTempRet0(0),0;var r=new ExceptionInfo(t);r.set_adjusted_ptr(t);var n=r.get_type();if(!n)return setTempRet0(0),t;for(var o in e){var a=e[o];if(0===a||a===n)break;var s=r.ptr+16;if(___cxa_can_catch(a,n,s))return setTempRet0(a),t}return setTempRet0(n),t},___cxa_find_matching_catch_2=()=>findMatchingCatch([]),___cxa_find_matching_catch_3=e=>findMatchingCatch([e]),___cxa_rethrow=()=>{var e=exceptionCaught.pop();e||abort("no exception to throw");var t=e.excPtr;throw e.get_rethrown()||(exceptionCaught.push(e),e.set_rethrown(!0),e.set_caught(!1),uncaughtExceptionCount++),exceptionLast=t},___cxa_rethrow_primary_exception=e=>{if(e){var t=new ExceptionInfo(e);exceptionCaught.push(t),t.set_rethrown(!0),___cxa_rethrow()}},___cxa_throw=(e,t,r)=>{throw new ExceptionInfo(e).init(t,r),uncaughtExceptionCount++,exceptionLast=e},___cxa_uncaught_exceptions=()=>uncaughtExceptionCount,PATH={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=PATH.isAbs(e),r="/"===e.substr(-1);return(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=PATH.splitPath(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=PATH.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return PATH.normalize(e.join("/"))},join2:(e,t)=>PATH.normalize(e+"/"+t)},initRandomFill=()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:FS.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,t=PATH.isAbs(n)}return(t?"/":"")+(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=PATH_FS.resolve(e).substr(1),t=PATH_FS.resolve(t).substr(1);for(var n=r(e.split("/")),o=r(t.split("/")),a=Math.min(n.length,o.length),s=a,i=0;i{for(var t=0,r=0;r=55296&&n<=57343?(t+=4,++r):t+=3}return t},stringToUTF8Array=(e,t,r,n)=>{if(!(n>0))return 0;for(var o=r,a=r+n-1,s=0;s=55296&&i<=57343)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++s);if(i<=127){if(r>=a)break;t[r++]=i}else if(i<=2047){if(r+1>=a)break;t[r++]=192|i>>6,t[r++]=128|63&i}else if(i<=65535){if(r+2>=a)break;t[r++]=224|i>>12,t[r++]=128|i>>6&63,t[r++]=128|63&i}else{if(r+3>=a)break;t[r++]=240|i>>18,t[r++]=128|i>>12&63,t[r++]=128|i>>6&63,t[r++]=128|63&i}}return t[r]=0,r-o};function intArrayFromString(e,t,r){var n=r>0?r:lengthBytesUTF8(e)+1,o=new Array(n),a=stringToUTF8Array(e,o,0,o.length);return t&&(o.length=a),o}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,t){TTY.ttys[e]={input:[],output:[],ops:t},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var t=TTY.ttys[e.node.rdev];if(!t)throw new FS.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,r,n,o){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var a=0,s=0;sFS_stdin_getChar(),put_char(e,t){null===t||10===t?(out(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(out(UTF8ArrayToString(e.output,0)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,r)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(err(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output,0)),e.output=[])}}},zeroMemory=(e,t)=>(HEAPU8.fill(0,e,e+t),e),alignMemory=(e,t)=>Math.ceil(e/t)*t,mmapAlloc=e=>{e=alignMemory(e,65536);var t=_emscripten_builtin_memalign(65536,e);return t?zeroMemory(t,e):0},MEMFS={ops_table:null,mount:e=>MEMFS.createNode(null,"/",16895,0),createNode(e,t,r,n){if(FS.isBlkdev(r)||FS.isFIFO(r))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var o=FS.createNode(e,t,r,n);return FS.isDir(o.mode)?(o.node_ops=MEMFS.ops_table.dir.node,o.stream_ops=MEMFS.ops_table.dir.stream,o.contents={}):FS.isFile(o.mode)?(o.node_ops=MEMFS.ops_table.file.node,o.stream_ops=MEMFS.ops_table.file.stream,o.usedBytes=0,o.contents=null):FS.isLink(o.mode)?(o.node_ops=MEMFS.ops_table.link.node,o.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(o.mode)&&(o.node_ops=MEMFS.ops_table.chrdev.node,o.stream_ops=MEMFS.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var n=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=FS.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,FS.isDir(e.mode)?t.size=4096:FS.isFile(e.mode)?t.size=e.usedBytes:FS.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&MEMFS.resizeFileStorage(e,t.size)},lookup(e,t){throw FS.genericErrors[44]},mknod:(e,t,r,n)=>MEMFS.createNode(e,t,r,n),rename(e,t,r){if(FS.isDir(e.mode)){var n;try{n=FS.lookupNode(t,r)}catch(e){}if(n)for(var o in n.contents)throw new FS.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=FS.lookupNode(e,t);for(var n in r.contents)throw new FS.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var n=MEMFS.createNode(e,t,41471,0);return n.link=r,n},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-o,n);if(s>8&&a.subarray)t.set(a.subarray(o,o+s),r);else for(var i=0;i0||r+t(MEMFS.stream_ops.write(e,t,0,n,r,!1),0)}},asyncLoad=(e,t,r,n)=>{var o=n?"":getUniqueRunDependency(`al ${e}`);readAsync(e,r=>{assert(r,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(r)),o&&removeRunDependency(o)},t=>{if(!r)throw`Loading data file "${e}" failed.`;r()}),o&&addRunDependency(o)},FS_createDataFile=(e,t,r,n,o,a)=>FS.createDataFile(e,t,r,n,o,a),preloadPlugins=Module.preloadPlugins||[],FS_handledByPreloadPlugin=(e,t,r,n)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return preloadPlugins.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,r,n),o=!0)}),o},FS_createPreloadedFile=(e,t,r,n,o,a,s,i,l,c)=>{var u=t?PATH_FS.resolve(PATH.join2(e,t)):e,m=getUniqueRunDependency(`cp ${u}`);function d(r){function d(r){c&&c(),i||FS_createDataFile(e,t,r,n,o,l),a&&a(),removeRunDependency(m)}FS_handledByPreloadPlugin(r,u,d,()=>{s&&s(),removeRunDependency(m)})||d(r)}addRunDependency(m),"string"==typeof r?asyncLoad(r,e=>d(e),s):d(r)},FS_modeStringToFlags=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t},FS_getMode=(e,t)=>{var r=0;return e&&(r|=365),t&&(r|=146),r},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(!(e=PATH_FS.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new FS.ErrnoError(32);for(var r=e.split("/").filter(e=>!!e),n=FS.root,o="/",a=0;a40)throw new FS.ErrnoError(32)}}return{path:o,node:n}},getPath(e){for(var t;;){if(FS.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?`${r}/${t}`:r+t:r}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var r=0,n=0;n>>0)%FS.nameTable.length},hashAddNode(e){var t=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[t],FS.nameTable[t]=e},hashRemoveNode(e){var t=FS.hashName(e.parent.id,e.name);if(FS.nameTable[t]===e)FS.nameTable[t]=e.name_next;else for(var r=FS.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode(e,t){var r=FS.mayLookup(e);if(r)throw new FS.ErrnoError(r,e);for(var n=FS.hashName(e.id,t),o=FS.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return FS.lookup(e,t)},createNode(e,t,r,n){var o=new FS.FSNode(e,t,r,n);return FS.hashAddNode(o),o},destroyNode(e){FS.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>FS.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){var t=FS.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{FS.lookupNode(e,t);return 20}catch(e){}return FS.nodePermissions(e,"wx")},mayDelete(e,t,r){var n;try{n=FS.lookupNode(e,t)}catch(e){return e.errno}var o=FS.nodePermissions(e,"wx");if(o)return o;if(r){if(!FS.isDir(n.mode))return 54;if(FS.isRoot(n)||FS.getPath(n)===FS.cwd())return 10}else if(FS.isDir(n.mode))return 31;return 0},mayOpen:(e,t)=>e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&("r"!==FS.flagsToPermissionString(t)||512&t)?31:FS.nodePermissions(e,FS.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var t=FS.getStream(e);if(!t)throw new FS.ErrnoError(8);return t},getStream:e=>FS.streams[e],createStream:(e,t=-1)=>(FS.FSStream||(FS.FSStream=function(){this.shared={}},FS.FSStream.prototype={},Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new FS.FSStream,e),-1==t&&(t=FS.nextfd()),e.fd=t,FS.streams[t]=e,e),closeStream(e){FS.streams[e]=null},chrdev_stream_ops:{open(e){var t=FS.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){FS.devices[e]={stream_ops:t}},getDevice:e=>FS.devices[e],getMounts(e){for(var t=[],r=[e];r.length;){var n=r.pop();t.push(n),r.push.apply(r,n.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var r=FS.getMounts(FS.root.mount),n=0;function o(e){return FS.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=r.length&&o(null)}r.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,r){var n,o="/"===r,a=!r;if(o&&FS.root)throw new FS.ErrnoError(10);if(!o&&!a){var s=FS.lookupPath(r,{follow_mount:!1});if(r=s.path,n=s.node,FS.isMountpoint(n))throw new FS.ErrnoError(10);if(!FS.isDir(n.mode))throw new FS.ErrnoError(54)}var i={type:e,opts:t,mountpoint:r,mounts:[]},l=e.mount(i);return l.mount=i,i.root=l,o?FS.root=l:n&&(n.mounted=i,n.mount&&n.mount.mounts.push(i)),l},unmount(e){var t=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(t.node))throw new FS.ErrnoError(28);var r=t.node,n=r.mounted,o=FS.getMounts(n);Object.keys(FS.nameTable).forEach(e=>{for(var t=FS.nameTable[e];t;){var r=t.name_next;o.includes(t.mount)&&FS.destroyNode(t),t=r}}),r.mounted=null;var a=r.mount.mounts.indexOf(n);r.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,r){var n=FS.lookupPath(e,{parent:!0}).node,o=PATH.basename(e);if(!o||"."===o||".."===o)throw new FS.ErrnoError(28);var a=FS.mayCreate(n,o);if(a)throw new FS.ErrnoError(a);if(!n.node_ops.mknod)throw new FS.ErrnoError(63);return n.node_ops.mknod(n,o,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,FS.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,FS.mknod(e,t,0)),mkdirTree(e,t){for(var r=e.split("/"),n="",o=0;o(void 0===r&&(r=t,t=438),t|=8192,FS.mknod(e,t,r)),symlink(e,t){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var r=FS.lookupPath(t,{parent:!0}).node;if(!r)throw new FS.ErrnoError(44);var n=PATH.basename(t),o=FS.mayCreate(r,n);if(o)throw new FS.ErrnoError(o);if(!r.node_ops.symlink)throw new FS.ErrnoError(63);return r.node_ops.symlink(r,n,e)},rename(e,t){var r,n,o=PATH.dirname(e),a=PATH.dirname(t),s=PATH.basename(e),i=PATH.basename(t);if(r=FS.lookupPath(e,{parent:!0}).node,n=FS.lookupPath(t,{parent:!0}).node,!r||!n)throw new FS.ErrnoError(44);if(r.mount!==n.mount)throw new FS.ErrnoError(75);var l,c=FS.lookupNode(r,s),u=PATH_FS.relative(e,a);if("."!==u.charAt(0))throw new FS.ErrnoError(28);if("."!==(u=PATH_FS.relative(t,o)).charAt(0))throw new FS.ErrnoError(55);try{l=FS.lookupNode(n,i)}catch(e){}if(c!==l){var m=FS.isDir(c.mode),d=FS.mayDelete(r,s,m);if(d)throw new FS.ErrnoError(d);if(d=l?FS.mayDelete(n,i,m):FS.mayCreate(n,i))throw new FS.ErrnoError(d);if(!r.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(c)||l&&FS.isMountpoint(l))throw new FS.ErrnoError(10);if(n!==r&&(d=FS.nodePermissions(r,"w")))throw new FS.ErrnoError(d);FS.hashRemoveNode(c);try{r.node_ops.rename(c,n,i)}catch(e){throw e}finally{FS.hashAddNode(c)}}},rmdir(e){var t=FS.lookupPath(e,{parent:!0}).node,r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!0);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.rmdir(t,r),FS.destroyNode(n)},readdir(e){var t=FS.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new FS.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=FS.lookupPath(e,{parent:!0}).node;if(!t)throw new FS.ErrnoError(44);var r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!1);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.unlink(t,r),FS.destroyNode(n)},readlink(e){var t=FS.lookupPath(e).node;if(!t)throw new FS.ErrnoError(44);if(!t.node_ops.readlink)throw new FS.ErrnoError(28);return PATH_FS.resolve(FS.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var r=FS.lookupPath(e,{follow:!t}).node;if(!r)throw new FS.ErrnoError(44);if(!r.node_ops.getattr)throw new FS.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>FS.stat(e,!0),chmod(e,t,r){var n;"string"==typeof e?n=FS.lookupPath(e,{follow:!r}).node:n=e;if(!n.node_ops.setattr)throw new FS.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&t|-4096&n.mode,timestamp:Date.now()})},lchmod(e,t){FS.chmod(e,t,!0)},fchmod(e,t){var r=FS.getStreamChecked(e);FS.chmod(r.node,t)},chown(e,t,r,n){var o;"string"==typeof e?o=FS.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new FS.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,r){FS.chown(e,t,r,!0)},fchown(e,t,r){var n=FS.getStreamChecked(e);FS.chown(n.node,t,r)},truncate(e,t){if(t<0)throw new FS.ErrnoError(28);var r;"string"==typeof e?r=FS.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(r.mode))throw new FS.ErrnoError(31);if(!FS.isFile(r.mode))throw new FS.ErrnoError(28);var n=FS.nodePermissions(r,"w");if(n)throw new FS.ErrnoError(n);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate(e,t){var r=FS.getStreamChecked(e);if(!(2097155&r.flags))throw new FS.ErrnoError(28);FS.truncate(r.node,t)},utime(e,t,r){var n=FS.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(t,r)})},open(e,t,r){if(""===e)throw new FS.ErrnoError(44);var n;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?FS_modeStringToFlags(t):t)?4095&r|32768:0,"object"==typeof e)n=e;else{e=PATH.normalize(e);try{n=FS.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(n){if(128&t)throw new FS.ErrnoError(20)}else n=FS.mknod(e,r,0),o=!0;if(!n)throw new FS.ErrnoError(44);if(FS.isChrdev(n.mode)&&(t&=-513),65536&t&&!FS.isDir(n.mode))throw new FS.ErrnoError(54);if(!o){var a=FS.mayOpen(n,t);if(a)throw new FS.ErrnoError(a)}512&t&&!o&&FS.truncate(n,0),t&=-131713;var s=FS.createStream({node:n,path:FS.getPath(n),flags:t,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!Module.logReadFiles||1&t||(FS.readFiles||(FS.readFiles={}),e in FS.readFiles||(FS.readFiles[e]=1)),s},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{FS.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read(e,t,r,n,o){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(1==(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var s=e.stream_ops.read(e,t,r,n,o);return a||(e.position+=s),s},write(e,t,r,n,o,a){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&1024&e.flags&&FS.llseek(e,0,2);var s=void 0!==o;if(s){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var i=e.stream_ops.write(e,t,r,n,o,a);return s||(e.position+=i),i},allocate(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(t<0||r<=0)throw new FS.ErrnoError(28);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap(e,t,r,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new FS.ErrnoError(2);if(1==(2097155&e.flags))throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);return e.stream_ops.mmap(e,t,r,n,o)},msync:(e,t,r,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,n,o):0,munmap:e=>0,ioctl(e,t,r){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var r,n=FS.open(e,t.flags),o=FS.stat(e).size,a=new Uint8Array(o);return FS.read(n,a,0,o,0),"utf8"===t.encoding?r=UTF8ArrayToString(a,0):"binary"===t.encoding&&(r=a),FS.close(n),r},writeFile(e,t,r={}){r.flags=r.flags||577;var n=FS.open(e,r.flags,r.mode);if("string"==typeof t){var o=new Uint8Array(lengthBytesUTF8(t)+1),a=stringToUTF8Array(t,o,0,o.length);FS.write(n,o,0,a,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");FS.write(n,t,0,t.byteLength,void 0,r.canOwn)}FS.close(n)},cwd:()=>FS.currentPath,chdir(e){var t=FS.lookupPath(e,{follow:!0});if(null===t.node)throw new FS.ErrnoError(44);if(!FS.isDir(t.node.mode))throw new FS.ErrnoError(54);var r=FS.nodePermissions(t.node,"x");if(r)throw new FS.ErrnoError(r);FS.currentPath=t.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(e,t,r,n,o)=>n}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=randomFill(e).byteLength),e[--t]);FS.createDevice("/dev","random",r),FS.createDevice("/dev","urandom",r),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var t=FS.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var r=+t,n=FS.getStreamChecked(r),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(){Module.stdin?FS.createDevice("/dev","stdin",Module.stdin):FS.symlink("/dev/tty","/dev/stdin"),Module.stdout?FS.createDevice("/dev","stdout",null,Module.stdout):FS.symlink("/dev/tty","/dev/stdout"),Module.stderr?FS.createDevice("/dev","stderr",null,Module.stderr):FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},ensureErrnoError(){FS.ErrnoError||(FS.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},FS.ErrnoError.prototype=new Error,FS.ErrnoError.prototype.constructor=FS.ErrnoError,[44].forEach(e=>{FS.genericErrors[e]=new FS.ErrnoError(e),FS.genericErrors[e].stack=""}))},staticInit(){FS.ensureErrnoError(),FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS:MEMFS}},init(e,t,r){FS.init.initialized=!0,FS.ensureErrnoError(),Module.stdin=e||Module.stdin,Module.stdout=t||Module.stdout,Module.stderr=r||Module.stderr,FS.createStandardStreams()},quit(){FS.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,n=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,s=1048576;o||(s=n);var i=this;i.setDataGetter(e=>{var t=e*s,o=(e+1)*s-1;if(o=Math.min(o,n-1),void 0===i.chunks[e]&&(i.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),n!==s&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):intArrayFromString(o.responseText||"",!0)})(t,o)),void 0===i.chunks[e])throw new Error("doXHR failed!");return i.chunks[e]}),!a&&n||(s=n=1,n=this.getter(0).length,s=n,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new a;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var i={isDevice:!1,contents:s}}else i={isDevice:!1,url:r};var l=FS.createFile(e,t,i,n,o);i.contents?l.contents=i.contents:i.url&&(l.contents=null,l.url=i.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,r,n,o){var a=e.node.contents;if(o>=a.length)return 0;var s=Math.min(a.length-o,n);if(a.slice)for(var i=0;i{var t=l.stream_ops[e];c[e]=function(){return FS.forceLoadFile(l),t.apply(null,arguments)}}),c.read=(e,t,r,n,o)=>(FS.forceLoadFile(l),u(e,t,r,n,o)),c.mmap=(e,t,r,n,o)=>{FS.forceLoadFile(l);var a=mmapAlloc(t);if(!a)throw new FS.ErrnoError(48);return u(e,HEAP8,a,t,r),{ptr:a,allocated:!0}},l.stream_ops=c,l}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,t,r){if(PATH.isAbs(t))return t;var n;-100===e?n=FS.cwd():n=SYSCALLS.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new FS.ErrnoError(44);return n}return PATH.join2(n,t)},doStat(e,t,r){try{var n=e(t)}catch(e){if(e&&e.node&&PATH.normalize(t)!==PATH.normalize(FS.getPath(e.node)))return-54;throw e}HEAP32[r>>2]=n.dev,HEAP32[r+4>>2]=n.mode,HEAPU32[r+8>>2]=n.nlink,HEAP32[r+12>>2]=n.uid,HEAP32[r+16>>2]=n.gid,HEAP32[r+20>>2]=n.rdev,tempI64=[n.size>>>0,(tempDouble=n.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+24>>2]=tempI64[0],HEAP32[r+28>>2]=tempI64[1],HEAP32[r+32>>2]=4096,HEAP32[r+36>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),s=n.ctime.getTime();return tempI64=[Math.floor(o/1e3)>>>0,(tempDouble=Math.floor(o/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+40>>2]=tempI64[0],HEAP32[r+44>>2]=tempI64[1],HEAPU32[r+48>>2]=o%1e3*1e3,tempI64=[Math.floor(a/1e3)>>>0,(tempDouble=Math.floor(a/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+56>>2]=tempI64[0],HEAP32[r+60>>2]=tempI64[1],HEAPU32[r+64>>2]=a%1e3*1e3,tempI64=[Math.floor(s/1e3)>>>0,(tempDouble=Math.floor(s/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+72>>2]=tempI64[0],HEAP32[r+76>>2]=tempI64[1],HEAPU32[r+80>>2]=s%1e3*1e3,tempI64=[n.ino>>>0,(tempDouble=n.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+88>>2]=tempI64[0],HEAP32[r+92>>2]=tempI64[1],0},doMsync(e,t,r,n,o){if(!FS.isFile(t.node.mode))throw new FS.ErrnoError(43);if(2&n)return 0;var a=HEAPU8.slice(e,e+r);FS.msync(t,a,o,r,n)},varargs:void 0,get(){var e=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},getp:()=>SYSCALLS.get(),getStr:e=>UTF8ToString(e),getStreamFromFD:e=>FS.getStreamChecked(e)};function ___syscall__newselect(e,t,r,n,o){try{for(var a=0,s=t?HEAP32[t>>2]:0,i=t?HEAP32[t+4>>2]:0,l=r?HEAP32[r>>2]:0,c=r?HEAP32[r+4>>2]:0,u=n?HEAP32[n>>2]:0,m=n?HEAP32[n+4>>2]:0,d=0,_=0,f=0,p=0,S=0,g=0,E=(t?HEAP32[t>>2]:0)|(r?HEAP32[r>>2]:0)|(n?HEAP32[n>>2]:0),h=(t?HEAP32[t+4>>2]:0)|(r?HEAP32[r+4>>2]:0)|(n?HEAP32[n+4>>2]:0),v=function(e,t,r,n){return e<32?t&n:r&n},F=0;F>2]:0)+(t?HEAP32[o+8>>2]:0)/1e6);D=w.stream_ops.poll(w,b)}1&D&&v(F,s,i,y)&&(F<32?d|=y:_|=y,a++),4&D&&v(F,l,c,y)&&(F<32?f|=y:p|=y,a++),2&D&&v(F,u,m,y)&&(F<32?S|=y:g|=y,a++)}}return t&&(HEAP32[t>>2]=d,HEAP32[t+4>>2]=_),r&&(HEAP32[r>>2]=f,HEAP32[r+4>>2]=p),n&&(HEAP32[n>>2]=S,HEAP32[n+4>>2]=g),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var SOCKFS={mount:e=>(Module.websocket=Module.websocket&&"object"==typeof Module.websocket?Module.websocket:{},Module.websocket._callbacks={},Module.websocket.on=function(e,t){return"function"==typeof t&&(this._callbacks[e]=t),this},Module.websocket.emit=function(e,t){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,t)},FS.createNode(null,"/",16895,0)),createSocket(e,t,r){if(1==(t&=-526337)&&r&&6!=r)throw new FS.ErrnoError(66);var n={family:e,type:t,protocol:r,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},o=SOCKFS.nextname(),a=FS.createNode(SOCKFS.root,o,49152,0);a.sock=n;var s=FS.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return n.stream=s,n},getSocket(e){var t=FS.getStream(e);return t&&FS.isSocket(t.node.mode)?t.node.sock:null},stream_ops:{poll(e){var t=e.node.sock;return t.sock_ops.poll(t)},ioctl(e,t,r){var n=e.node.sock;return n.sock_ops.ioctl(n,t,r)},read(e,t,r,n,o){var a=e.node.sock,s=a.sock_ops.recvmsg(a,n);return s?(t.set(s.buffer,r),s.buffer.length):0},write(e,t,r,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,t,r,n)},close(e){var t=e.node.sock;t.sock_ops.close(t)}},nextname:()=>(SOCKFS.nextname.current||(SOCKFS.nextname.current=0),"socket["+SOCKFS.nextname.current+++"]"),websocket_sock_ops:{createPeer(e,t,r){var n;if("object"==typeof t&&(n=t,t=null,r=null),n)if(n._socket)t=n._socket.remoteAddress,r=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");t=o[1],r=parseInt(o[2],10)}else try{var a=Module.websocket&&"object"==typeof Module.websocket,s="ws:#".replace("#","//");if(a&&"string"==typeof Module.websocket.url&&(s=Module.websocket.url),"ws://"===s||"wss://"===s){var i=t.split("/");s=s+i[0]+":"+r+"/"+i.slice(1).join("/")}var l="binary";a&&"string"==typeof Module.websocket.subprotocol&&(l=Module.websocket.subprotocol);var c=void 0;"null"!==l&&(c=l=l.replace(/^ +| +$/g,"").split(/ *, */)),a&&null===Module.websocket.subprotocol&&(l="null",c=void 0),(n=new WebSocket(s,c)).binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}var u={addr:t,port:r,socket:n,dgram_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,u),SOCKFS.websocket_sock_ops.handlePeerEvents(e,u),2===e.type&&void 0!==e.sport&&u.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),u},getPeer:(e,t,r)=>e.peers[t+":"+r],addPeer(e,t){e.peers[t.addr+":"+t.port]=t},removePeer(e,t){delete e.peers[t.addr+":"+t.port]},handlePeerEvents(e,t){var r=!0,n=function(){Module.websocket.emit("open",e.stream.fd);try{for(var r=t.dgram_send_queue.shift();r;)t.socket.send(r),r=t.dgram_send_queue.shift()}catch(e){t.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(assert(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=r;if(r=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var a=n[8]<<8|n[9];return SOCKFS.websocket_sock_ops.removePeer(e,t),t.port=a,void SOCKFS.websocket_sock_ops.addPeer(e,t)}e.recv_queue.push({addr:t.addr,port:t.port,data:n}),Module.websocket.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(t.socket.on("open",n),t.socket.on("message",function(e,t){t&&o(new Uint8Array(e).buffer)}),t.socket.on("close",function(){Module.websocket.emit("close",e.stream.fd)}),t.socket.on("error",function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(t.socket.onopen=n,t.socket.onclose=function(){Module.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){o(e.data)},t.socket.onerror=function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(1===e.type&&e.server)return e.pending.length?65:0;var t=0,r=1===e.type?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!r||r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=65),(!r||r&&r.socket.readyState===r.socket.OPEN)&&(t|=4),(r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=16),t},ioctl(e,t,r){if(21531===t){var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),HEAP32[r>>2]=n,0}return 28},close(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var t=Object.keys(e.peers),r=0;r{var t=SOCKFS.getSocket(e);if(!t)throw new FS.ErrnoError(8);return t},setErrNo=e=>(HEAP32[___errno_location()>>2]=e,e),inetNtop4=e=>(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var t="",r=0,n=0,o=0,a=0,s=0,i=0,l=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,u="";for(i=0;i<5;i++)if(0!==l[i]){c=!1;break}if(c){if(u=inetNtop4(l[6]|l[7]<<16),-1===l[5])return t="::ffff:",t+=u;if(0===l[5])return t="::","0.0.0.0"===u&&(u=""),"0.0.0.1"===u&&(u="1"),t+=u}for(r=0;r<8;r++)0===l[r]&&(r-o>1&&(s=0),o=r,s++),s>n&&(a=r-(n=s)+1);for(r=0;r<8;r++)n>1&&0===l[r]&&r>=a&&r{var r,n=HEAP16[e>>1],o=_ntohs(HEAPU16[e+2>>1]);switch(n){case 2:if(16!==t)return{errno:28};r=HEAP32[e+4>>2],r=inetNtop4(r);break;case 10:if(28!==t)return{errno:28};r=[HEAP32[e+8>>2],HEAP32[e+12>>2],HEAP32[e+16>>2],HEAP32[e+20>>2]],r=inetNtop6(r);break;default:return{errno:5}}return{family:n,addr:r,port:o}},inetPton4=e=>{for(var t=e.split("."),r=0;r<4;r++){var n=Number(t[r]);if(isNaN(n))return null;t[r]=n}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var t,r,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jstoi_q(t[t.length-4])+256*jstoi_q(t[t.length-3]),t[t.length-3]=jstoi_q(t[t.length-2])+256*jstoi_q(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),n=0,o=0,r=0;rDNS.address_map.names[e]?DNS.address_map.names[e]:null},getSocketAddress=(e,t,r)=>{if(r&&0===e)return null;var n=readSockaddr(e,t);if(n.errno)throw new FS.ErrnoError(n.errno);return n.addr=DNS.lookup_addr(n.addr)||n.addr,n};function ___syscall_connect(e,t,r,n,o,a){try{var s=getSocketFromFD(e),i=getSocketAddress(t,r);return s.sock_ops.connect(s,i.addr,i.port),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_faccessat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),-8&r)return-28;var o=FS.lookupPath(t,{follow:!0}).node;if(!o)return-44;var a="";return 4&r&&(a+="r"),2&r&&(a+="w"),1&r&&(a+="x"),a&&FS.nodePermissions(o,a)?-2:0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fcntl64(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 0:if((o=SYSCALLS.get())<0)return-28;for(;FS.streams[o];)o++;return FS.createStream(n,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return n.flags;case 4:var o=SYSCALLS.get();return n.flags|=o,0;case 5:o=SYSCALLS.getp();return HEAP16[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return setErrNo(28),-1}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fstat64(e,t){try{var r=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,r.path,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var stringToUTF8=(e,t,r)=>stringToUTF8Array(e,HEAPU8,t,r);function ___syscall_getcwd(e,t){try{if(0===t)return-28;var r=FS.cwd(),n=lengthBytesUTF8(r)+1;return t>>0,(tempDouble=l,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t+a>>2]=tempI64[0],HEAP32[t+a+4>>2]=tempI64[1],tempI64=[(i+1)*o>>>0,(tempDouble=(i+1)*o,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t+a+8>>2]=tempI64[0],HEAP32[t+a+12>>2]=tempI64[1],HEAP16[t+a+16>>1]=280,HEAP8[t+a+18|0]=c,stringToUTF8(u,t+a+19,256),a+=o,i+=1}return FS.llseek(n,i*o,0),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_ioctl(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return n.tty?0:-59;case 21505:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var o=n.tty.ops.ioctl_tcgets(n),a=SYSCALLS.getp();HEAP32[a>>2]=o.c_iflag||0,HEAP32[a+4>>2]=o.c_oflag||0,HEAP32[a+8>>2]=o.c_cflag||0,HEAP32[a+12>>2]=o.c_lflag||0;for(var s=0;s<32;s++)HEAP8[a+s+17|0]=o.c_cc[s]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){a=SYSCALLS.getp();var i=HEAP32[a>>2],l=HEAP32[a+4>>2],c=HEAP32[a+8>>2],u=HEAP32[a+12>>2],m=[];for(s=0;s<32;s++)m.push(HEAP8[a+s+17|0]);return n.tty.ops.ioctl_tcsets(n.tty,t,{c_iflag:i,c_oflag:l,c_cflag:c,c_lflag:u,c_cc:m})}return 0;case 21519:if(!n.tty)return-59;a=SYSCALLS.getp();return HEAP32[a>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:a=SYSCALLS.getp();return FS.ioctl(n,t,a);case 21523:if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var d=n.tty.ops.ioctl_tiocgwinsz(n.tty);a=SYSCALLS.getp();HEAP16[a>>1]=d[0],HEAP16[a+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_lstat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.lstat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_mkdirat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),"/"===(t=PATH.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),FS.mkdir(t,r,0),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_newfstatat(e,t,r,n){try{t=SYSCALLS.getStr(t);var o=256&n,a=4096&n;return n&=-6401,t=SYSCALLS.calculateAt(e,t,a),SYSCALLS.doStat(o?FS.lstat:FS.stat,t,r)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_openat(e,t,r,n){SYSCALLS.varargs=n;try{t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t);var o=n?SYSCALLS.get():0;return FS.open(t,r,o).fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_readlinkat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),n<=0)return-28;var o=FS.readlink(t),a=Math.min(n,lengthBytesUTF8(o)),s=HEAP8[r+a];return stringToUTF8(o,r,n+1),HEAP8[r+a]=s,a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_rmdir(e){try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_socket(e,t,r){try{return SOCKFS.createSocket(e,t,r).stream.fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_stat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_unlinkat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),0===r?FS.unlink(t):512===r?FS.rmdir(t):abort("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var nowIsMonotonic=!0,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic,convertI32PairToI53Checked=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN;function __gmtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getUTCSeconds(),HEAP32[r+4>>2]=o.getUTCMinutes(),HEAP32[r+8>>2]=o.getUTCHours(),HEAP32[r+12>>2]=o.getUTCDate(),HEAP32[r+16>>2]=o.getUTCMonth(),HEAP32[r+20>>2]=o.getUTCFullYear()-1900,HEAP32[r+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),s=(o.getTime()-a)/864e5|0;HEAP32[r+28>>2]=s}var isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>(isLeapYear(e.getFullYear())?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()]+e.getDate()-1;function __localtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getSeconds(),HEAP32[r+4>>2]=o.getMinutes(),HEAP32[r+8>>2]=o.getHours(),HEAP32[r+12>>2]=o.getDate(),HEAP32[r+16>>2]=o.getMonth(),HEAP32[r+20>>2]=o.getFullYear()-1900,HEAP32[r+24>>2]=o.getDay();var a=0|ydayFromDate(o);HEAP32[r+28>>2]=a,HEAP32[r+36>>2]=-60*o.getTimezoneOffset();var s=new Date(o.getFullYear(),0,1),i=new Date(o.getFullYear(),6,1).getTimezoneOffset(),l=s.getTimezoneOffset(),c=0|(i!=l&&o.getTimezoneOffset()==Math.min(l,i));HEAP32[r+32>>2]=c}var __mktime_js=function(e){var t=(()=>{var t=new Date(HEAP32[e+20>>2]+1900,HEAP32[e+16>>2],HEAP32[e+12>>2],HEAP32[e+8>>2],HEAP32[e+4>>2],HEAP32[e>>2],0),r=HEAP32[e+32>>2],n=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),i=Math.min(s,a);if(r<0)HEAP32[e+32>>2]=Number(a!=s&&i==n);else if(r>0!=(i==n)){var l=Math.max(s,a),c=r>0?i:l;t.setTime(t.getTime()+6e4*(c-n))}HEAP32[e+24>>2]=t.getDay();var u=0|ydayFromDate(t);return HEAP32[e+28>>2]=u,HEAP32[e>>2]=t.getSeconds(),HEAP32[e+4>>2]=t.getMinutes(),HEAP32[e+8>>2]=t.getHours(),HEAP32[e+12>>2]=t.getDate(),HEAP32[e+16>>2]=t.getMonth(),HEAP32[e+20>>2]=t.getYear(),t.getTime()/1e3})();return setTempRet0((tempDouble=t,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)),t>>>0};function __mmap_js(e,t,r,n,o,a,s,i){var l=convertI32PairToI53Checked(o,a);try{if(isNaN(l))return 61;var c=SYSCALLS.getStreamFromFD(n),u=FS.mmap(c,e,l,t,r),m=u.ptr;return HEAP32[s>>2]=u.allocated,HEAPU32[i>>2]=m,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function __munmap_js(e,t,r,n,o,a,s){var i=convertI32PairToI53Checked(a,s);try{if(isNaN(i))return 61;var l=SYSCALLS.getStreamFromFD(o);2&r&&SYSCALLS.doMsync(e,l,t,n,i),FS.munmap(l)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var _emscripten_get_now,stringToNewUTF8=e=>{var t=lengthBytesUTF8(e)+1,r=_malloc(t);return r&&stringToUTF8(e,r,t),r},__tzset_js=(e,t,r)=>{var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),s=o.getTimezoneOffset(),i=a.getTimezoneOffset(),l=Math.max(s,i);function c(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}HEAPU32[e>>2]=60*l,HEAP32[t>>2]=Number(s!=i);var u=c(o),m=c(a),d=stringToNewUTF8(u),_=stringToNewUTF8(m);i>2]=d,HEAPU32[r+4>>2]=_):(HEAPU32[r>>2]=_,HEAPU32[r+4>>2]=d)},_abort=()=>{abort("")},readEmAsmArgsArray=[],readEmAsmArgs=(e,t)=>{var r;for(readEmAsmArgsArray.length=0;r=HEAPU8[e++];){var n=105!=r;t+=(n&=112!=r)&&t%8?4:0,readEmAsmArgsArray.push(112==r?HEAPU32[t>>2]:105==r?HEAP32[t>>2]:HEAPF64[t>>3]),t+=n?8:4}return readEmAsmArgsArray},runEmAsmFunction=(e,t,r)=>{var n=readEmAsmArgs(t,r);return ASM_CONSTS[e].apply(null,n)},_emscripten_asm_const_int=(e,t,r)=>runEmAsmFunction(e,t,r),_emscripten_date_now=()=>Date.now(),_emscripten_errn=(e,t)=>err(UTF8ToString(e,t)),getHeapMax=()=>2147483648,_emscripten_get_heap_max=()=>getHeapMax();_emscripten_get_now=()=>performance.now();var reallyNegative=e=>e<0||0===e&&1/e==-1/0,convertI32PairToI53=(e,t)=>(e>>>0)+4294967296*t,convertU32PairToI53=(e,t)=>(e>>>0)+4294967296*(t>>>0),reSign=(e,t)=>{if(e<=0)return e;var r=t<=32?Math.abs(1<=r&&(t<=32||e>r)&&(e=-2*r+e),e},unSign=(e,t)=>e>=0?e:t<=32?2*Math.abs(1<{for(var t=e;HEAPU8[t];)++t;return t-e},formatString=(e,t)=>{var r=e,n=t;function o(e){var t;return n=function(e,t){return"double"!==t&&"i64"!==t||7&e&&(e+=4),e}(n,e),"double"===e?(t=HEAPF64[n>>3],n+=8):"i64"==e?(t=[HEAP32[n>>2],HEAP32[n+4>>2]],n+=8):(e="i32",t=HEAP32[n>>2],n+=4),t}for(var a,s,i,l=[];;){var c=r;if(0===(a=HEAP8[r|0]))break;if(s=HEAP8[r+1|0],37==a){var u=!1,m=!1,d=!1,_=!1,f=!1;e:for(;;){switch(s){case 43:u=!0;break;case 45:m=!0;break;case 35:d=!0;break;case 48:if(_)break e;_=!0;break;case 32:f=!0;break;default:break e}r++,s=HEAP8[r+1|0]}var p=0;if(42==s)p=o("i32"),r++,s=HEAP8[r+1|0];else for(;s>=48&&s<=57;)p=10*p+(s-48),r++,s=HEAP8[r+1|0];var S,g=!1,E=-1;if(46==s){if(E=0,g=!0,r++,42==(s=HEAP8[r+1|0]))E=o("i32"),r++;else for(;;){var h=HEAP8[r+1|0];if(h<48||h>57)break;E=10*E+(h-48),r++}s=HEAP8[r+1|0]}switch(E<0&&(E=6,g=!1),String.fromCharCode(s)){case"h":104==HEAP8[r+2|0]?(r++,S=1):S=2;break;case"l":108==HEAP8[r+2|0]?(r++,S=8):S=4;break;case"L":case"q":case"j":S=8;break;case"z":case"t":case"I":S=4;break;default:S=null}switch(S&&r++,s=HEAP8[r+1|0],String.fromCharCode(s)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":var v=100==s||105==s;if(i=o("i"+8*(S=S||4)),8==S&&(i=117==s?convertU32PairToI53(i[0],i[1]):convertI32PairToI53(i[0],i[1])),S<=4){var F=Math.pow(256,S)-1;i=(v?reSign:unSign)(i&F,8*S)}var y=Math.abs(i),w="";if(100==s||105==s)k=reSign(i,8*S).toString(10);else if(117==s)k=unSign(i,8*S).toString(10),i=Math.abs(i);else if(111==s)k=(d?"0":"")+y.toString(8);else if(120==s||88==s){if(w=d&&0!=i?"0x":"",i<0){i=-i,k=(y-1).toString(16);for(var D=[],b=0;b=0&&(u?w="+"+w:f&&(w=" "+w)),"-"==k.charAt(0)&&(w="-"+w,k=k.substr(1));w.length+k.lengthN&&N>=-4?(s=(103==s?"f":"F").charCodeAt(0),E-=N+1):(s=(103==s?"e":"E").charCodeAt(0),E--),T=Math.min(E,20)}101==s||69==s?(k=i.toExponential(T),/[eE][-+]\d$/.test(k)&&(k=k.slice(0,-1)+"0"+k.slice(-1))):102!=s&&70!=s||(k=i.toFixed(T),0===i&&reallyNegative(i)&&(k="-"+k));var P=k.split("e");if(A&&!d)for(;P[0].length>1&&P[0].includes(".")&&("0"==P[0].slice(-1)||"."==P[0].slice(-1));)P[0]=P[0].slice(0,-1);else for(d&&-1==k.indexOf(".")&&(P[0]+=".");E>T++;)P[0]+="0";k=P[0]+(P.length>1?"e"+P[1]:""),69==s&&(k=k.toUpperCase()),i>=0&&(u?k="+"+k:f&&(k=" "+k))}else k=(i<0?"-":"")+"inf",_=!1;for(;k.length0;)l.push(32);m||l.push(o("i8"));break;case"n":var M=o("i32*");HEAP32[M>>2]=l.length;break;case"%":l.push(a);break;default:for(b=c;b{warnOnce.shown||(warnOnce.shown={}),warnOnce.shown[e]||(warnOnce.shown[e]=1,err(e))};function getCallstack(e){var t=jsStackTrace(),r=t.lastIndexOf("_emscripten_log"),n=t.lastIndexOf("_emscripten_get_callstack"),o=t.indexOf("\n",Math.max(r,n))+1;t=t.slice(o),8&e&&"undefined"==typeof emscripten_source_map&&(warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'),e^=8,e|=16);var a=t.split("\n");t="";var s=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"),i=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"),l=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var c in a){var u=a[c],m="",d="",_=0,f=0,p=l.exec(u);if(p&&5==p.length)m=p[1],d=p[2],_=p[3],f=p[4];else{if((p=s.exec(u))||(p=i.exec(u)),!(p&&p.length>=4)){t+=u+"\n";continue}m=p[1],d=p[2],_=p[3],f=0|p[4]}var S=!1;if(8&e){var g=emscripten_source_map.originalPositionFor({line:_,column:f});(S=g&&g.source)&&(64&e&&(g.source=g.source.substring(g.source.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=` at ${m} (${g.source}:${g.line}:${g.column})\n`)}(16&e||!S)&&(64&e&&(d=d.substring(d.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=(S?` = ${m}`:` at ${m}`)+` (${d}:${_}:${f})\n`)}return t=t.replace(/\s+$/,"")}var emscriptenLog=(e,t)=>{24&e&&(t=t.replace(/\s+$/,""),t+=(t.length>0?"\n":"")+getCallstack(e)),1&e?4&e||2&e?err(t):out(t):6&e?err(t):out(t)},_emscripten_log=(e,t,r)=>{var n=formatString(t,r),o=UTF8ArrayToString(n,0);emscriptenLog(e,o)},growMemory=e=>{var t=(e-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch(e){}},_emscripten_resize_heap=e=>{var t=HEAPU8.length;e>>>=0;var r=getHeapMax();if(e>r)return!1;for(var n=(e,t)=>e+(t-e%t)%t,o=1;o<=4;o*=2){var a=t*(1+.2/o);a=Math.min(a,e+100663296);var s=Math.min(r,n(Math.max(e,a),65536));if(growMemory(s))return!0}return!1},ENV={},getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(var t in ENV)void 0===ENV[t]?delete e[t]:e[t]=ENV[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToAscii=(e,t)=>{for(var r=0;r{var r=0;return getEnvStrings().forEach((n,o)=>{var a=t+r;HEAPU32[e+4*o>>2]=a,stringToAscii(n,a),r+=n.length+1}),0},_environ_sizes_get=(e,t)=>{var r=getEnvStrings();HEAPU32[e>>2]=r.length;var n=0;return r.forEach(e=>n+=e.length+1),HEAPU32[t>>2]=n,0};function _fd_close(e){try{var t=SYSCALLS.getStreamFromFD(e);return FS.close(t),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doReadv=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.read(e,HEAP8,s,i,n);if(l<0)return-1;if(o+=l,l>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}function _fd_seek(e,t,r,n,o){var a=convertI32PairToI53Checked(t,r);try{if(isNaN(a))return 61;var s=SYSCALLS.getStreamFromFD(e);return FS.llseek(s,a,n),tempI64=[s.position>>>0,(tempDouble=s.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[o>>2]=tempI64[0],HEAP32[o+4>>2]=tempI64[1],s.getdents&&0===a&&0===n&&(s.getdents=null),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doWritev=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.write(e,HEAP8,s,i,n);if(l<0)return-1;o+=l,void 0!==n&&(n+=l)}return o};function _fd_write(e,t,r,n){try{var o=SYSCALLS.getStreamFromFD(e),a=doWritev(o,t,r);return HEAPU32[n>>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var wasmTable,functionsInTableMap,arraySum=(e,t)=>{for(var r=0,n=0;n<=t;r+=e[n++]);return r},MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31],MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31],addDays=(e,t)=>{for(var r=new Date(e.getTime());t>0;){var n=isLeapYear(r.getFullYear()),o=r.getMonth(),a=(n?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[o];if(!(t>a-r.getDate()))return r.setDate(r.getDate()+t),r;t-=a-r.getDate()+1,r.setDate(1),o<11?r.setMonth(o+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r},writeArrayToMemory=(e,t)=>{HEAP8.set(e,t)},_strftime=(e,t,r,n)=>{var o=HEAPU32[n+40>>2],a={tm_sec:HEAP32[n>>2],tm_min:HEAP32[n+4>>2],tm_hour:HEAP32[n+8>>2],tm_mday:HEAP32[n+12>>2],tm_mon:HEAP32[n+16>>2],tm_year:HEAP32[n+20>>2],tm_wday:HEAP32[n+24>>2],tm_yday:HEAP32[n+28>>2],tm_isdst:HEAP32[n+32>>2],tm_gmtoff:HEAP32[n+36>>2],tm_zone:o?UTF8ToString(o):""},s=UTF8ToString(r),i={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in i)s=s.replace(new RegExp(l,"g"),i[l]);var c=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"];function m(e,t,r){for(var n="number"==typeof e?e.toString():e||"";n.length0?1:0}var n;return 0===(n=r(e.getFullYear()-t.getFullYear()))&&0===(n=r(e.getMonth()-t.getMonth()))&&(n=r(e.getDate()-t.getDate())),n}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function p(e){var t=addDays(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),n=new Date(t.getFullYear()+1,0,4),o=f(r),a=f(n);return _(o,t)<=0?_(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var S={"%a":e=>c[e.tm_wday].substring(0,3),"%A":e=>c[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>d((e.tm_year+1900)/100|0,2),"%d":e=>d(e.tm_mday,2),"%e":e=>m(e.tm_mday,2," "),"%g":e=>p(e).toString().substring(2),"%G":e=>p(e),"%H":e=>d(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":e=>d(e.tm_mday+arraySum(isLeapYear(e.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,e.tm_mon-1),3),"%m":e=>d(e.tm_mon+1,2),"%M":e=>d(e.tm_min,2),"%n":()=>"\n","%p":e=>e.tm_hour>=0&&e.tm_hour<12?"AM":"PM","%S":e=>d(e.tm_sec,2),"%t":()=>"\t","%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&isLeapYear(e.tm_year)||(t=1)}}else{t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(4==n||5==n&&isLeapYear(e.tm_year%400-1))&&t++}return d(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>"%"};for(var l in s=s.replace(/%%/g,"\0\0"),S)s.includes(l)&&(s=s.replace(new RegExp(l,"g"),S[l](a)));var g=intArrayFromString(s=s.replace(/\0\0/g,"%"),!1);return g.length>t?0:(writeArrayToMemory(g,e),g.length-1)},_strftime_l=(e,t,r,n,o)=>_strftime(e,t,r,n),getWasmTableEntry=e=>wasmTable.get(e),uleb128Encode=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var t={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"},r={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},n=1;n{var r=e.slice(0,1),n=e.slice(1),o={i:127,p:127,j:126,f:125,d:124};t.push(96),uleb128Encode(n.length,t);for(var a=0;a{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function(sigToWasmTypes(t),e);var r=[1];generateFuncType(t,r);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(r.length,n),n.push.apply(n,r),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var o=new WebAssembly.Module(new Uint8Array(n));return new WebAssembly.Instance(o,{e:{f:e}}).exports.f},updateTableMap=(e,t)=>{if(functionsInTableMap)for(var r=e;r(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1},setWasmTableEntry=(e,t)=>wasmTable.set(e,t),addFunction=(e,t)=>{var r=getFunctionAddress(e);if(r)return r;var n=getEmptyTableSlot();try{setWasmTableEntry(n,e)}catch(r){if(!(r instanceof TypeError))throw r;var o=convertJsFunctionToWasm(e,t);setWasmTableEntry(n,o)}return functionsInTableMap.set(e,n),n},stringToUTF8OnStack=e=>{var t=lengthBytesUTF8(e)+1,r=stackAlloc(t);return stringToUTF8(e,r,t),r},FSNode=function(e,t,r,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=FS.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n},readMode=365,writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(e){e?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(e){e?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}}),FS.FSNode=FSNode,FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit();var calledRun,wasmImports={CreateDirectoryFetcher:_CreateDirectoryFetcher,DDN_ConvertElement:_DDN_ConvertElement,DDN_CreateDDNResult:_DDN_CreateDDNResult,DDN_CreateDDNResultItem:_DDN_CreateDDNResultItem,DDN_CreateIntermediateResultUnits:_DDN_CreateIntermediateResultUnits,DDN_CreateParameters:_DDN_CreateParameters,DDN_CreateTargetRoiDefConditionFilter:_DDN_CreateTargetRoiDefConditionFilter,DDN_CreateTaskAlgEntity:_DDN_CreateTaskAlgEntity,DDN_HasSection:_DDN_HasSection,DDN_ReadTaskSetting:_DDN_ReadTaskSetting,DLR_ConvertElement:_DLR_ConvertElement,DLR_CreateBufferedCharacterItemSet:_DLR_CreateBufferedCharacterItemSet,DLR_CreateIntermediateResultUnits:_DLR_CreateIntermediateResultUnits,DLR_CreateParameters:_DLR_CreateParameters,DLR_CreateRecognizedTextLinesResult:_DLR_CreateRecognizedTextLinesResult,DLR_CreateTargetRoiDefConditionFilter:_DLR_CreateTargetRoiDefConditionFilter,DLR_CreateTaskAlgEntity:_DLR_CreateTaskAlgEntity,DLR_CreateTextLineResultItem:_DLR_CreateTextLineResultItem,DLR_ReadTaskSetting:_DLR_ReadTaskSetting,DMImage_GetDIB:_DMImage_GetDIB,DMImage_GetOrientation:_DMImage_GetOrientation,DeleteDirectoryFetcher:_DeleteDirectoryFetcher,_ZN19LabelRecognizerWasm10getVersionEv:__ZN19LabelRecognizerWasm10getVersionEv,_ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv:__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv,_ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv:__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv,_ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi:__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi,_ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb:__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb,_ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb:__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb,_ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb:__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb,_ZN19LabelRecognizerWasm12DlrWasmClassC1Ev:__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev,_ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE:__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE,_ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE:__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE,_ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE:__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE,_ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE:__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE,_ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE:__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE,_ZN22DocumentNormalizerWasm10getVersionEv:__ZN22DocumentNormalizerWasm10getVersionEv,_ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv:__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv,_ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi:__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi,_ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii:__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii,_ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE,_ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev:__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev,_ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE:__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE,_ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE:__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE,_ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E:__ZN5nsync13nsync_cv_waitEPNS_11nsync_cv_s_EPNS_11nsync_mu_s_E,_ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E:__ZN5nsync15nsync_cv_signalEPNS_11nsync_cv_s_E,_ZN9dynamsoft7utility14CUtilityModule10GetVersionEv:__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv,__assert_fail:___assert_fail,__cxa_begin_catch:___cxa_begin_catch,__cxa_end_catch:___cxa_end_catch,__cxa_find_matching_catch_2:___cxa_find_matching_catch_2,__cxa_find_matching_catch_3:___cxa_find_matching_catch_3,__cxa_rethrow:___cxa_rethrow,__cxa_rethrow_primary_exception:___cxa_rethrow_primary_exception,__cxa_throw:___cxa_throw,__cxa_uncaught_exceptions:___cxa_uncaught_exceptions,__resumeException:___resumeException,__syscall__newselect:___syscall__newselect,__syscall_connect:___syscall_connect,__syscall_faccessat:___syscall_faccessat,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_readlinkat:___syscall_readlinkat,__syscall_rmdir:___syscall_rmdir,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_unlinkat:___syscall_unlinkat,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_mktime_js:__mktime_js,_mmap_js:__mmap_js,_munmap_js:__munmap_js,_tzset_js:__tzset_js,abort:_abort,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_date_now:_emscripten_date_now,emscripten_errn:_emscripten_errn,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_log:_emscripten_log,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,invoke_diii:invoke_diii,invoke_fiii:invoke_fiii,invoke_i:invoke_i,invoke_ii:invoke_ii,invoke_iii:invoke_iii,invoke_iiii:invoke_iiii,invoke_iiiii:invoke_iiiii,invoke_iiiiid:invoke_iiiiid,invoke_iiiiii:invoke_iiiiii,invoke_iiiiiii:invoke_iiiiiii,invoke_iiiiiiii:invoke_iiiiiiii,invoke_iiiiiiiiiiii:invoke_iiiiiiiiiiii,invoke_iiiiij:invoke_iiiiij,invoke_j:invoke_j,invoke_ji:invoke_ji,invoke_jii:invoke_jii,invoke_jiiii:invoke_jiiii,invoke_v:invoke_v,invoke_vi:invoke_vi,invoke_vii:invoke_vii,invoke_viid:invoke_viid,invoke_viii:invoke_viii,invoke_viiii:invoke_viiii,invoke_viiiiiii:invoke_viiiiiii,invoke_viiiiiiiiii:invoke_viiiiiiiiii,invoke_viiiiiiiiiiiiiii:invoke_viiiiiiiiiiiiiii,strftime:_strftime,strftime_l:_strftime_l},wasmExports=createWasm();function invoke_iiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(e,t){var r=stackSave();try{return getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(e,t,r){var n=stackSave();try{return getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(e,t,r){var n=stackSave();try{getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(e,t,r,n,o){var a=stackSave();try{getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(e){var t=stackSave();try{getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(e,t,r,n,o){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(e,t){var r=stackSave();try{getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(e,t,r,n,o,a,s){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiid(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_diii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(e){var t=stackSave();try{return getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,m){var d=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,m)}catch(e){if(stackRestore(d),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u){var m=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u)}catch(e){if(stackRestore(m),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,m,d,_,f,p){var S=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,m,d,_,f,p)}catch(e){if(stackRestore(S),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_j(e){var t=stackSave();try{return dynCall_j(e)}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(e,t){var r=stackSave();try{return dynCall_ji(e,t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(e,t,r){var n=stackSave();try{return dynCall_jii(e,t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiij(e,t,r,n,o,a,s){var i=stackSave();try{return dynCall_iiiiij(e,t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(e,t,r,n,o){var a=stackSave();try{return dynCall_jiiii(e,t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function run(){function e(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT||(initRuntime(),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)]()[UTF8ToString(r)]()),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack((new(self[UTF8ToString(e)]))[UTF8ToString(t)](UTF8ToString(r))),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>{self[UTF8ToString(e)](null,UTF8ToString(t).trim(),UTF8ToString(r),n)},"viiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)][UTF8ToString(r)](UTF8ToString(n))?"":self[UTF8ToString(e)][UTF8ToString(t)]),"iiiii")),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun()))}runDependencies>0||(preRun(),runDependencies>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()))}if(Module.addFunction=addFunction,Module.stringToUTF8OnStack=stringToUTF8OnStack,dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)},Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();run(); \ No newline at end of file diff --git a/dist/dynamsoft-barcode-reader-bundle-ml.wasm b/dist/dynamsoft-barcode-reader-bundle-ml.wasm deleted file mode 100644 index 0bc5c4c..0000000 Binary files a/dist/dynamsoft-barcode-reader-bundle-ml.wasm and /dev/null differ diff --git a/dist/dynamsoft-barcode-reader-bundle.js b/dist/dynamsoft-barcode-reader-bundle.js index fe7f074..2dec9f7 100644 --- a/dist/dynamsoft-barcode-reader-bundle.js +++ b/dist/dynamsoft-barcode-reader-bundle.js @@ -1 +1 @@ -var read_,readAsync,readBinary,Module=void 0!==Module?Module:{},moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(e,t)=>{throw t},ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!0,ENVIRONMENT_IS_NODE=!1,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:"undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=0!==scriptDirectory.indexOf("blob:")?scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1):"",read_=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),readAsync=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var wasmBinary,out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit),Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,noExitRuntime=Module.noExitRuntime||!0;"object"!=typeof WebAssembly&&abort("no native wasm support detected");var EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,ABORT=!1;function assert(e,t){e||abort(t)}function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e)}var __ATPRERUN__=[],__ATINIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,Module.noFSInit||FS.init.initialized||FS.init(),FS.ignorePermissions=!1,TTY.init(),SOCKFS.root=FS.mount(SOCKFS,{},null),callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module.postRun)for("function"==typeof Module.postRun&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(e){return e}function addRunDependency(e){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}function removeRunDependency(e){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}function abort(e){throw Module.onAbort&&Module.onAbort(e),err(e="Aborted("+e+")"),ABORT=!0,EXITSTATUS=1,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}var wasmBinaryFile,tempDouble,tempI64,dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(e){return e.startsWith(dataURIPrefix)}function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(e){return wasmBinary||!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER||"function"!=typeof fetch?Promise.resolve().then(()=>getBinarySync(e)):fetch(e,{credentials:"same-origin"}).then(t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";return t.arrayBuffer()}).catch(()=>getBinarySync(e))}function instantiateArrayBuffer(e,t,r){return getBinaryPromise(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(r,e=>{err(`failed to asynchronously prepare wasm: ${e}`),abort(e)})}function instantiateAsync(e,t,r,n){return e||"function"!=typeof WebAssembly.instantiateStreaming||isDataURI(t)||"function"!=typeof fetch?instantiateArrayBuffer(t,r,n):fetch(t,{credentials:"same-origin"}).then(e=>WebAssembly.instantiateStreaming(e,r).then(n,function(e){return err(`wasm streaming compile failed: ${e}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(t,r,n)}))}function createWasm(){var e={env:wasmImports,wasi_snapshot_preview1:wasmImports};function t(e,t){return wasmExports=e.exports,wasmMemory=wasmExports.memory,updateMemoryViews(),wasmTable=wasmExports.__indirect_function_table,addOnInit(wasmExports.__wasm_call_ctors),exportWasmSymbols(wasmExports),removeRunDependency("wasm-instantiate"),wasmExports}if(addRunDependency("wasm-instantiate"),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return err(`Module.instantiateWasm callback failed with error: ${e}`),!1}return instantiateAsync(wasmBinary,wasmBinaryFile,e,function(e){t(e.instance)}),{}}isDataURI(wasmBinaryFile="dynamsoft-barcode-reader-bundle.wasm")||(wasmBinaryFile=locateFile(wasmBinaryFile));var callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},asmjsMangle=e=>("__main_argc_argv"==e&&(e="main"),0==e.indexOf("dynCall_")||["stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0"].includes(e)?e:"_"+e),exportWasmSymbols=e=>{for(var t in e){var r=asmjsMangle(t);this[r]=Module[r]=e[t]}};function _CreateDirectoryFetcher(){abort("missing function: CreateDirectoryFetcher")}function _DDN_ConvertElement(){abort("missing function: DDN_ConvertElement")}function _DDN_CreateDDNResult(){abort("missing function: DDN_CreateDDNResult")}function _DDN_CreateDDNResultItem(){abort("missing function: DDN_CreateDDNResultItem")}function _DDN_CreateIntermediateResultUnits(){abort("missing function: DDN_CreateIntermediateResultUnits")}function _DDN_CreateParameters(){abort("missing function: DDN_CreateParameters")}function _DDN_CreateTargetRoiDefConditionFilter(){abort("missing function: DDN_CreateTargetRoiDefConditionFilter")}function _DDN_CreateTaskAlgEntity(){abort("missing function: DDN_CreateTaskAlgEntity")}function _DDN_HasSection(){abort("missing function: DDN_HasSection")}function _DDN_ReadTaskSetting(){abort("missing function: DDN_ReadTaskSetting")}function _DLR_ConvertElement(){abort("missing function: DLR_ConvertElement")}function _DLR_CreateBufferedCharacterItemSet(){abort("missing function: DLR_CreateBufferedCharacterItemSet")}function _DLR_CreateIntermediateResultUnits(){abort("missing function: DLR_CreateIntermediateResultUnits")}function _DLR_CreateParameters(){abort("missing function: DLR_CreateParameters")}function _DLR_CreateRecognizedTextLinesResult(){abort("missing function: DLR_CreateRecognizedTextLinesResult")}function _DLR_CreateTargetRoiDefConditionFilter(){abort("missing function: DLR_CreateTargetRoiDefConditionFilter")}function _DLR_CreateTaskAlgEntity(){abort("missing function: DLR_CreateTaskAlgEntity")}function _DLR_CreateTextLineResultItem(){abort("missing function: DLR_CreateTextLineResultItem")}function _DLR_ReadTaskSetting(){abort("missing function: DLR_ReadTaskSetting")}function _DMImage_GetDIB(){abort("missing function: DMImage_GetDIB")}function _DMImage_GetOrientation(){abort("missing function: DMImage_GetOrientation")}function _DNN_CreateSession(){abort("missing function: DNN_CreateSession")}function _DNN_GetRegionByIndex(){abort("missing function: DNN_GetRegionByIndex")}function _DNN_ReleaseRegion(){abort("missing function: DNN_ReleaseRegion")}function _DNN_ReleaseSession(){abort("missing function: DNN_ReleaseSession")}function _DNN_RunDeblurInference(){abort("missing function: DNN_RunDeblurInference")}function _DNN_RunDeblurInference_C1(){abort("missing function: DNN_RunDeblurInference_C1")}function _DNN_RunLocalizationInference(){abort("missing function: DNN_RunLocalizationInference")}function _DeleteDirectoryFetcher(){abort("missing function: DeleteDirectoryFetcher")}function __ZN19LabelRecognizerWasm10getVersionEv(){abort("missing function: _ZN19LabelRecognizerWasm10getVersionEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi")}function __ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb")}function __ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClassC1Ev(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev")}function __ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE(){abort("missing function: _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE")}function __ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE(){abort("missing function: _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE")}function __ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE")}function __ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE")}function __ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE(){abort("missing function: _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE")}function __ZN22DocumentNormalizerWasm10getVersionEv(){abort("missing function: _ZN22DocumentNormalizerWasm10getVersionEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii")}function __ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE")}function __ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev")}function __ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE")}function __ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE")}function __ZN9dynamsoft7utility14CUtilityModule10GetVersionEv(){abort("missing function: _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv")}_CreateDirectoryFetcher.stub=!0,_DDN_ConvertElement.stub=!0,_DDN_CreateDDNResult.stub=!0,_DDN_CreateDDNResultItem.stub=!0,_DDN_CreateIntermediateResultUnits.stub=!0,_DDN_CreateParameters.stub=!0,_DDN_CreateTargetRoiDefConditionFilter.stub=!0,_DDN_CreateTaskAlgEntity.stub=!0,_DDN_HasSection.stub=!0,_DDN_ReadTaskSetting.stub=!0,_DLR_ConvertElement.stub=!0,_DLR_CreateBufferedCharacterItemSet.stub=!0,_DLR_CreateIntermediateResultUnits.stub=!0,_DLR_CreateParameters.stub=!0,_DLR_CreateRecognizedTextLinesResult.stub=!0,_DLR_CreateTargetRoiDefConditionFilter.stub=!0,_DLR_CreateTaskAlgEntity.stub=!0,_DLR_CreateTextLineResultItem.stub=!0,_DLR_ReadTaskSetting.stub=!0,_DMImage_GetDIB.stub=!0,_DMImage_GetOrientation.stub=!0,_DNN_CreateSession.stub=!0,_DNN_GetRegionByIndex.stub=!0,_DNN_ReleaseRegion.stub=!0,_DNN_ReleaseSession.stub=!0,_DNN_RunDeblurInference.stub=!0,_DNN_RunDeblurInference_C1.stub=!0,_DNN_RunLocalizationInference.stub=!0,_DeleteDirectoryFetcher.stub=!0,__ZN19LabelRecognizerWasm10getVersionEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev.stub=!0,__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE.stub=!0,__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE.stub=!0,__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE.stub=!0,__ZN22DocumentNormalizerWasm10getVersionEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev.stub=!0,__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE.stub=!0,__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE.stub=!0,__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv.stub=!0;var UTF8Decoder="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,UTF8ArrayToString=(e,t,r)=>{for(var n=t+r,o=t;e[o]&&!(o>=n);)++o;if(o-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&c)}}else a+=String.fromCharCode((31&i)<<6|s)}else a+=String.fromCharCode(i)}return a},UTF8ToString=(e,t)=>e?UTF8ArrayToString(HEAPU8,e,t):"",___assert_fail=(e,t,r,n)=>{abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[t?UTF8ToString(t):"unknown filename",r,n?UTF8ToString(n):"unknown function"])},exceptionCaught=[],uncaughtExceptionCount=0,___cxa_begin_catch=e=>{var t=new ExceptionInfo(e);return t.get_caught()||(t.set_caught(!0),uncaughtExceptionCount--),t.set_rethrown(!1),exceptionCaught.push(t),___cxa_increment_exception_refcount(t.excPtr),t.get_exception_ptr()},exceptionLast=0,___cxa_end_catch=()=>{_setThrew(0,0);var e=exceptionCaught.pop();___cxa_decrement_exception_refcount(e.excPtr),exceptionLast=0};function ExceptionInfo(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){HEAPU32[this.ptr+4>>2]=e},this.get_type=function(){return HEAPU32[this.ptr+4>>2]},this.set_destructor=function(e){HEAPU32[this.ptr+8>>2]=e},this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,HEAP8[this.ptr+12|0]=e},this.get_caught=function(){return 0!=HEAP8[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,HEAP8[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=HEAP8[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){HEAPU32[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]},this.get_exception_ptr=function(){if(___cxa_is_pointer_type(this.get_type()))return HEAPU32[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var ___resumeException=e=>{throw exceptionLast||(exceptionLast=e),exceptionLast},findMatchingCatch=e=>{var t=exceptionLast;if(!t)return setTempRet0(0),0;var r=new ExceptionInfo(t);r.set_adjusted_ptr(t);var n=r.get_type();if(!n)return setTempRet0(0),t;for(var o in e){var a=e[o];if(0===a||a===n)break;var i=r.ptr+16;if(___cxa_can_catch(a,n,i))return setTempRet0(a),t}return setTempRet0(n),t},___cxa_find_matching_catch_2=()=>findMatchingCatch([]),___cxa_find_matching_catch_3=e=>findMatchingCatch([e]),___cxa_rethrow=()=>{var e=exceptionCaught.pop();e||abort("no exception to throw");var t=e.excPtr;throw e.get_rethrown()||(exceptionCaught.push(e),e.set_rethrown(!0),e.set_caught(!1),uncaughtExceptionCount++),exceptionLast=t},___cxa_rethrow_primary_exception=e=>{if(e){var t=new ExceptionInfo(e);exceptionCaught.push(t),t.set_rethrown(!0),___cxa_rethrow()}},___cxa_throw=(e,t,r)=>{throw new ExceptionInfo(e).init(t,r),uncaughtExceptionCount++,exceptionLast=e},___cxa_uncaught_exceptions=()=>uncaughtExceptionCount,PATH={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=PATH.isAbs(e),r="/"===e.substr(-1);return(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=PATH.splitPath(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=PATH.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return PATH.normalize(e.join("/"))},join2:(e,t)=>PATH.normalize(e+"/"+t)},initRandomFill=()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:FS.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,t=PATH.isAbs(n)}return(t?"/":"")+(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=PATH_FS.resolve(e).substr(1),t=PATH_FS.resolve(t).substr(1);for(var n=r(e.split("/")),o=r(t.split("/")),a=Math.min(n.length,o.length),i=a,s=0;s{for(var t=0,r=0;r=55296&&n<=57343?(t+=4,++r):t+=3}return t},stringToUTF8Array=(e,t,r,n)=>{if(!(n>0))return 0;for(var o=r,a=r+n-1,i=0;i=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i);if(s<=127){if(r>=a)break;t[r++]=s}else if(s<=2047){if(r+1>=a)break;t[r++]=192|s>>6,t[r++]=128|63&s}else if(s<=65535){if(r+2>=a)break;t[r++]=224|s>>12,t[r++]=128|s>>6&63,t[r++]=128|63&s}else{if(r+3>=a)break;t[r++]=240|s>>18,t[r++]=128|s>>12&63,t[r++]=128|s>>6&63,t[r++]=128|63&s}}return t[r]=0,r-o};function intArrayFromString(e,t,r){var n=r>0?r:lengthBytesUTF8(e)+1,o=new Array(n),a=stringToUTF8Array(e,o,0,o.length);return t&&(o.length=a),o}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,t){TTY.ttys[e]={input:[],output:[],ops:t},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var t=TTY.ttys[e.node.rdev];if(!t)throw new FS.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,r,n,o){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var a=0,i=0;iFS_stdin_getChar(),put_char(e,t){null===t||10===t?(out(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(out(UTF8ArrayToString(e.output,0)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,r)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(err(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output,0)),e.output=[])}}},mmapAlloc=e=>{abort()},MEMFS={ops_table:null,mount:e=>MEMFS.createNode(null,"/",16895,0),createNode(e,t,r,n){if(FS.isBlkdev(r)||FS.isFIFO(r))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var o=FS.createNode(e,t,r,n);return FS.isDir(o.mode)?(o.node_ops=MEMFS.ops_table.dir.node,o.stream_ops=MEMFS.ops_table.dir.stream,o.contents={}):FS.isFile(o.mode)?(o.node_ops=MEMFS.ops_table.file.node,o.stream_ops=MEMFS.ops_table.file.stream,o.usedBytes=0,o.contents=null):FS.isLink(o.mode)?(o.node_ops=MEMFS.ops_table.link.node,o.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(o.mode)&&(o.node_ops=MEMFS.ops_table.chrdev.node,o.stream_ops=MEMFS.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var n=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=FS.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,FS.isDir(e.mode)?t.size=4096:FS.isFile(e.mode)?t.size=e.usedBytes:FS.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&MEMFS.resizeFileStorage(e,t.size)},lookup(e,t){throw FS.genericErrors[44]},mknod:(e,t,r,n)=>MEMFS.createNode(e,t,r,n),rename(e,t,r){if(FS.isDir(e.mode)){var n;try{n=FS.lookupNode(t,r)}catch(e){}if(n)for(var o in n.contents)throw new FS.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=FS.lookupNode(e,t);for(var n in r.contents)throw new FS.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var n=MEMFS.createNode(e,t,41471,0);return n.link=r,n},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var i=Math.min(e.node.usedBytes-o,n);if(i>8&&a.subarray)t.set(a.subarray(o,o+i),r);else for(var s=0;s0||r+t(MEMFS.stream_ops.write(e,t,0,n,r,!1),0)}},asyncLoad=(e,t,r,n)=>{var o=n?"":getUniqueRunDependency(`al ${e}`);readAsync(e,r=>{assert(r,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(r)),o&&removeRunDependency(o)},t=>{if(!r)throw`Loading data file "${e}" failed.`;r()}),o&&addRunDependency(o)},FS_createDataFile=(e,t,r,n,o,a)=>FS.createDataFile(e,t,r,n,o,a),preloadPlugins=Module.preloadPlugins||[],FS_handledByPreloadPlugin=(e,t,r,n)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return preloadPlugins.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,r,n),o=!0)}),o},FS_createPreloadedFile=(e,t,r,n,o,a,i,s,l,c)=>{var u=t?PATH_FS.resolve(PATH.join2(e,t)):e,m=getUniqueRunDependency(`cp ${u}`);function d(r){function d(r){c&&c(),s||FS_createDataFile(e,t,r,n,o,l),a&&a(),removeRunDependency(m)}FS_handledByPreloadPlugin(r,u,d,()=>{i&&i(),removeRunDependency(m)})||d(r)}addRunDependency(m),"string"==typeof r?asyncLoad(r,e=>d(e),i):d(r)},FS_modeStringToFlags=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t},FS_getMode=(e,t)=>{var r=0;return e&&(r|=365),t&&(r|=146),r},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(!(e=PATH_FS.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new FS.ErrnoError(32);for(var r=e.split("/").filter(e=>!!e),n=FS.root,o="/",a=0;a40)throw new FS.ErrnoError(32)}}return{path:o,node:n}},getPath(e){for(var t;;){if(FS.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?`${r}/${t}`:r+t:r}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var r=0,n=0;n>>0)%FS.nameTable.length},hashAddNode(e){var t=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[t],FS.nameTable[t]=e},hashRemoveNode(e){var t=FS.hashName(e.parent.id,e.name);if(FS.nameTable[t]===e)FS.nameTable[t]=e.name_next;else for(var r=FS.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode(e,t){var r=FS.mayLookup(e);if(r)throw new FS.ErrnoError(r,e);for(var n=FS.hashName(e.id,t),o=FS.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return FS.lookup(e,t)},createNode(e,t,r,n){var o=new FS.FSNode(e,t,r,n);return FS.hashAddNode(o),o},destroyNode(e){FS.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>FS.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){var t=FS.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{FS.lookupNode(e,t);return 20}catch(e){}return FS.nodePermissions(e,"wx")},mayDelete(e,t,r){var n;try{n=FS.lookupNode(e,t)}catch(e){return e.errno}var o=FS.nodePermissions(e,"wx");if(o)return o;if(r){if(!FS.isDir(n.mode))return 54;if(FS.isRoot(n)||FS.getPath(n)===FS.cwd())return 10}else if(FS.isDir(n.mode))return 31;return 0},mayOpen:(e,t)=>e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&("r"!==FS.flagsToPermissionString(t)||512&t)?31:FS.nodePermissions(e,FS.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var t=FS.getStream(e);if(!t)throw new FS.ErrnoError(8);return t},getStream:e=>FS.streams[e],createStream:(e,t=-1)=>(FS.FSStream||(FS.FSStream=function(){this.shared={}},FS.FSStream.prototype={},Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new FS.FSStream,e),-1==t&&(t=FS.nextfd()),e.fd=t,FS.streams[t]=e,e),closeStream(e){FS.streams[e]=null},chrdev_stream_ops:{open(e){var t=FS.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){FS.devices[e]={stream_ops:t}},getDevice:e=>FS.devices[e],getMounts(e){for(var t=[],r=[e];r.length;){var n=r.pop();t.push(n),r.push.apply(r,n.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var r=FS.getMounts(FS.root.mount),n=0;function o(e){return FS.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=r.length&&o(null)}r.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,r){var n,o="/"===r,a=!r;if(o&&FS.root)throw new FS.ErrnoError(10);if(!o&&!a){var i=FS.lookupPath(r,{follow_mount:!1});if(r=i.path,n=i.node,FS.isMountpoint(n))throw new FS.ErrnoError(10);if(!FS.isDir(n.mode))throw new FS.ErrnoError(54)}var s={type:e,opts:t,mountpoint:r,mounts:[]},l=e.mount(s);return l.mount=s,s.root=l,o?FS.root=l:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),l},unmount(e){var t=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(t.node))throw new FS.ErrnoError(28);var r=t.node,n=r.mounted,o=FS.getMounts(n);Object.keys(FS.nameTable).forEach(e=>{for(var t=FS.nameTable[e];t;){var r=t.name_next;o.includes(t.mount)&&FS.destroyNode(t),t=r}}),r.mounted=null;var a=r.mount.mounts.indexOf(n);r.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,r){var n=FS.lookupPath(e,{parent:!0}).node,o=PATH.basename(e);if(!o||"."===o||".."===o)throw new FS.ErrnoError(28);var a=FS.mayCreate(n,o);if(a)throw new FS.ErrnoError(a);if(!n.node_ops.mknod)throw new FS.ErrnoError(63);return n.node_ops.mknod(n,o,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,FS.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,FS.mknod(e,t,0)),mkdirTree(e,t){for(var r=e.split("/"),n="",o=0;o(void 0===r&&(r=t,t=438),t|=8192,FS.mknod(e,t,r)),symlink(e,t){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var r=FS.lookupPath(t,{parent:!0}).node;if(!r)throw new FS.ErrnoError(44);var n=PATH.basename(t),o=FS.mayCreate(r,n);if(o)throw new FS.ErrnoError(o);if(!r.node_ops.symlink)throw new FS.ErrnoError(63);return r.node_ops.symlink(r,n,e)},rename(e,t){var r,n,o=PATH.dirname(e),a=PATH.dirname(t),i=PATH.basename(e),s=PATH.basename(t);if(r=FS.lookupPath(e,{parent:!0}).node,n=FS.lookupPath(t,{parent:!0}).node,!r||!n)throw new FS.ErrnoError(44);if(r.mount!==n.mount)throw new FS.ErrnoError(75);var l,c=FS.lookupNode(r,i),u=PATH_FS.relative(e,a);if("."!==u.charAt(0))throw new FS.ErrnoError(28);if("."!==(u=PATH_FS.relative(t,o)).charAt(0))throw new FS.ErrnoError(55);try{l=FS.lookupNode(n,s)}catch(e){}if(c!==l){var m=FS.isDir(c.mode),d=FS.mayDelete(r,i,m);if(d)throw new FS.ErrnoError(d);if(d=l?FS.mayDelete(n,s,m):FS.mayCreate(n,s))throw new FS.ErrnoError(d);if(!r.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(c)||l&&FS.isMountpoint(l))throw new FS.ErrnoError(10);if(n!==r&&(d=FS.nodePermissions(r,"w")))throw new FS.ErrnoError(d);FS.hashRemoveNode(c);try{r.node_ops.rename(c,n,s)}catch(e){throw e}finally{FS.hashAddNode(c)}}},rmdir(e){var t=FS.lookupPath(e,{parent:!0}).node,r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!0);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.rmdir(t,r),FS.destroyNode(n)},readdir(e){var t=FS.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new FS.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=FS.lookupPath(e,{parent:!0}).node;if(!t)throw new FS.ErrnoError(44);var r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!1);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.unlink(t,r),FS.destroyNode(n)},readlink(e){var t=FS.lookupPath(e).node;if(!t)throw new FS.ErrnoError(44);if(!t.node_ops.readlink)throw new FS.ErrnoError(28);return PATH_FS.resolve(FS.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var r=FS.lookupPath(e,{follow:!t}).node;if(!r)throw new FS.ErrnoError(44);if(!r.node_ops.getattr)throw new FS.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>FS.stat(e,!0),chmod(e,t,r){var n;"string"==typeof e?n=FS.lookupPath(e,{follow:!r}).node:n=e;if(!n.node_ops.setattr)throw new FS.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&t|-4096&n.mode,timestamp:Date.now()})},lchmod(e,t){FS.chmod(e,t,!0)},fchmod(e,t){var r=FS.getStreamChecked(e);FS.chmod(r.node,t)},chown(e,t,r,n){var o;"string"==typeof e?o=FS.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new FS.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,r){FS.chown(e,t,r,!0)},fchown(e,t,r){var n=FS.getStreamChecked(e);FS.chown(n.node,t,r)},truncate(e,t){if(t<0)throw new FS.ErrnoError(28);var r;"string"==typeof e?r=FS.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(r.mode))throw new FS.ErrnoError(31);if(!FS.isFile(r.mode))throw new FS.ErrnoError(28);var n=FS.nodePermissions(r,"w");if(n)throw new FS.ErrnoError(n);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate(e,t){var r=FS.getStreamChecked(e);if(!(2097155&r.flags))throw new FS.ErrnoError(28);FS.truncate(r.node,t)},utime(e,t,r){var n=FS.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(t,r)})},open(e,t,r){if(""===e)throw new FS.ErrnoError(44);var n;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?FS_modeStringToFlags(t):t)?4095&r|32768:0,"object"==typeof e)n=e;else{e=PATH.normalize(e);try{n=FS.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(n){if(128&t)throw new FS.ErrnoError(20)}else n=FS.mknod(e,r,0),o=!0;if(!n)throw new FS.ErrnoError(44);if(FS.isChrdev(n.mode)&&(t&=-513),65536&t&&!FS.isDir(n.mode))throw new FS.ErrnoError(54);if(!o){var a=FS.mayOpen(n,t);if(a)throw new FS.ErrnoError(a)}512&t&&!o&&FS.truncate(n,0),t&=-131713;var i=FS.createStream({node:n,path:FS.getPath(n),flags:t,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return i.stream_ops.open&&i.stream_ops.open(i),!Module.logReadFiles||1&t||(FS.readFiles||(FS.readFiles={}),e in FS.readFiles||(FS.readFiles[e]=1)),i},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{FS.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read(e,t,r,n,o){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(1==(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var i=e.stream_ops.read(e,t,r,n,o);return a||(e.position+=i),i},write(e,t,r,n,o,a){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&1024&e.flags&&FS.llseek(e,0,2);var i=void 0!==o;if(i){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,t,r,n,o,a);return i||(e.position+=s),s},allocate(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(t<0||r<=0)throw new FS.ErrnoError(28);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap(e,t,r,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new FS.ErrnoError(2);if(1==(2097155&e.flags))throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);return e.stream_ops.mmap(e,t,r,n,o)},msync:(e,t,r,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,n,o):0,munmap:e=>0,ioctl(e,t,r){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var r,n=FS.open(e,t.flags),o=FS.stat(e).size,a=new Uint8Array(o);return FS.read(n,a,0,o,0),"utf8"===t.encoding?r=UTF8ArrayToString(a,0):"binary"===t.encoding&&(r=a),FS.close(n),r},writeFile(e,t,r={}){r.flags=r.flags||577;var n=FS.open(e,r.flags,r.mode);if("string"==typeof t){var o=new Uint8Array(lengthBytesUTF8(t)+1),a=stringToUTF8Array(t,o,0,o.length);FS.write(n,o,0,a,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");FS.write(n,t,0,t.byteLength,void 0,r.canOwn)}FS.close(n)},cwd:()=>FS.currentPath,chdir(e){var t=FS.lookupPath(e,{follow:!0});if(null===t.node)throw new FS.ErrnoError(44);if(!FS.isDir(t.node.mode))throw new FS.ErrnoError(54);var r=FS.nodePermissions(t.node,"x");if(r)throw new FS.ErrnoError(r);FS.currentPath=t.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(e,t,r,n,o)=>n}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=randomFill(e).byteLength),e[--t]);FS.createDevice("/dev","random",r),FS.createDevice("/dev","urandom",r),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var t=FS.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var r=+t,n=FS.getStreamChecked(r),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(){Module.stdin?FS.createDevice("/dev","stdin",Module.stdin):FS.symlink("/dev/tty","/dev/stdin"),Module.stdout?FS.createDevice("/dev","stdout",null,Module.stdout):FS.symlink("/dev/tty","/dev/stdout"),Module.stderr?FS.createDevice("/dev","stderr",null,Module.stderr):FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},ensureErrnoError(){FS.ErrnoError||(FS.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},FS.ErrnoError.prototype=new Error,FS.ErrnoError.prototype.constructor=FS.ErrnoError,[44].forEach(e=>{FS.genericErrors[e]=new FS.ErrnoError(e),FS.genericErrors[e].stack=""}))},staticInit(){FS.ensureErrnoError(),FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS:MEMFS}},init(e,t,r){FS.init.initialized=!0,FS.ensureErrnoError(),Module.stdin=e||Module.stdin,Module.stdout=t||Module.stdout,Module.stderr=r||Module.stderr,FS.createStandardStreams()},quit(){FS.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,n=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,i=1048576;o||(i=n);var s=this;s.setDataGetter(e=>{var t=e*i,o=(e+1)*i-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),n!==i&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):intArrayFromString(o.responseText||"",!0)})(t,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!a&&n||(i=n=1,n=this.getter(0).length,i=n,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=i,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i=new a;Object.defineProperties(i,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:i}}else s={isDevice:!1,url:r};var l=FS.createFile(e,t,s,n,o);s.contents?l.contents=s.contents:s.url&&(l.contents=null,l.url=s.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,r,n,o){var a=e.node.contents;if(o>=a.length)return 0;var i=Math.min(a.length-o,n);if(a.slice)for(var s=0;s{var t=l.stream_ops[e];c[e]=function(){return FS.forceLoadFile(l),t.apply(null,arguments)}}),c.read=(e,t,r,n,o)=>(FS.forceLoadFile(l),u(e,t,r,n,o)),c.mmap=(e,t,r,n,o)=>{FS.forceLoadFile(l);var a=mmapAlloc(t);if(!a)throw new FS.ErrnoError(48);return u(e,HEAP8,a,t,r),{ptr:a,allocated:!0}},l.stream_ops=c,l}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,t,r){if(PATH.isAbs(t))return t;var n;-100===e?n=FS.cwd():n=SYSCALLS.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new FS.ErrnoError(44);return n}return PATH.join2(n,t)},doStat(e,t,r){try{var n=e(t)}catch(e){if(e&&e.node&&PATH.normalize(t)!==PATH.normalize(FS.getPath(e.node)))return-54;throw e}HEAP32[r>>2]=n.dev,HEAP32[r+4>>2]=n.mode,HEAPU32[r+8>>2]=n.nlink,HEAP32[r+12>>2]=n.uid,HEAP32[r+16>>2]=n.gid,HEAP32[r+20>>2]=n.rdev,tempI64=[n.size>>>0,(tempDouble=n.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+24>>2]=tempI64[0],HEAP32[r+28>>2]=tempI64[1],HEAP32[r+32>>2]=4096,HEAP32[r+36>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),i=n.ctime.getTime();return tempI64=[Math.floor(o/1e3)>>>0,(tempDouble=Math.floor(o/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+40>>2]=tempI64[0],HEAP32[r+44>>2]=tempI64[1],HEAPU32[r+48>>2]=o%1e3*1e3,tempI64=[Math.floor(a/1e3)>>>0,(tempDouble=Math.floor(a/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+56>>2]=tempI64[0],HEAP32[r+60>>2]=tempI64[1],HEAPU32[r+64>>2]=a%1e3*1e3,tempI64=[Math.floor(i/1e3)>>>0,(tempDouble=Math.floor(i/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+72>>2]=tempI64[0],HEAP32[r+76>>2]=tempI64[1],HEAPU32[r+80>>2]=i%1e3*1e3,tempI64=[n.ino>>>0,(tempDouble=n.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+88>>2]=tempI64[0],HEAP32[r+92>>2]=tempI64[1],0},doMsync(e,t,r,n,o){if(!FS.isFile(t.node.mode))throw new FS.ErrnoError(43);if(2&n)return 0;var a=HEAPU8.slice(e,e+r);FS.msync(t,a,o,r,n)},varargs:void 0,get(){var e=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},getp:()=>SYSCALLS.get(),getStr:e=>UTF8ToString(e),getStreamFromFD:e=>FS.getStreamChecked(e)};function ___syscall__newselect(e,t,r,n,o){try{for(var a=0,i=t?HEAP32[t>>2]:0,s=t?HEAP32[t+4>>2]:0,l=r?HEAP32[r>>2]:0,c=r?HEAP32[r+4>>2]:0,u=n?HEAP32[n>>2]:0,m=n?HEAP32[n+4>>2]:0,d=0,_=0,f=0,g=0,p=0,S=0,h=(t?HEAP32[t>>2]:0)|(r?HEAP32[r>>2]:0)|(n?HEAP32[n>>2]:0),E=(t?HEAP32[t+4>>2]:0)|(r?HEAP32[r+4>>2]:0)|(n?HEAP32[n+4>>2]:0),v=function(e,t,r,n){return e<32?t&n:r&n},F=0;F>2]:0)+(t?HEAP32[o+8>>2]:0)/1e6);D=w.stream_ops.poll(w,b)}1&D&&v(F,i,s,y)&&(F<32?d|=y:_|=y,a++),4&D&&v(F,l,c,y)&&(F<32?f|=y:g|=y,a++),2&D&&v(F,u,m,y)&&(F<32?p|=y:S|=y,a++)}}return t&&(HEAP32[t>>2]=d,HEAP32[t+4>>2]=_),r&&(HEAP32[r>>2]=f,HEAP32[r+4>>2]=g),n&&(HEAP32[n>>2]=p,HEAP32[n+4>>2]=S),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var SOCKFS={mount:e=>(Module.websocket=Module.websocket&&"object"==typeof Module.websocket?Module.websocket:{},Module.websocket._callbacks={},Module.websocket.on=function(e,t){return"function"==typeof t&&(this._callbacks[e]=t),this},Module.websocket.emit=function(e,t){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,t)},FS.createNode(null,"/",16895,0)),createSocket(e,t,r){if(1==(t&=-526337)&&r&&6!=r)throw new FS.ErrnoError(66);var n={family:e,type:t,protocol:r,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},o=SOCKFS.nextname(),a=FS.createNode(SOCKFS.root,o,49152,0);a.sock=n;var i=FS.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return n.stream=i,n},getSocket(e){var t=FS.getStream(e);return t&&FS.isSocket(t.node.mode)?t.node.sock:null},stream_ops:{poll(e){var t=e.node.sock;return t.sock_ops.poll(t)},ioctl(e,t,r){var n=e.node.sock;return n.sock_ops.ioctl(n,t,r)},read(e,t,r,n,o){var a=e.node.sock,i=a.sock_ops.recvmsg(a,n);return i?(t.set(i.buffer,r),i.buffer.length):0},write(e,t,r,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,t,r,n)},close(e){var t=e.node.sock;t.sock_ops.close(t)}},nextname:()=>(SOCKFS.nextname.current||(SOCKFS.nextname.current=0),"socket["+SOCKFS.nextname.current+++"]"),websocket_sock_ops:{createPeer(e,t,r){var n;if("object"==typeof t&&(n=t,t=null,r=null),n)if(n._socket)t=n._socket.remoteAddress,r=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");t=o[1],r=parseInt(o[2],10)}else try{var a=Module.websocket&&"object"==typeof Module.websocket,i="ws:#".replace("#","//");if(a&&"string"==typeof Module.websocket.url&&(i=Module.websocket.url),"ws://"===i||"wss://"===i){var s=t.split("/");i=i+s[0]+":"+r+"/"+s.slice(1).join("/")}var l="binary";a&&"string"==typeof Module.websocket.subprotocol&&(l=Module.websocket.subprotocol);var c=void 0;"null"!==l&&(c=l=l.replace(/^ +| +$/g,"").split(/ *, */)),a&&null===Module.websocket.subprotocol&&(l="null",c=void 0),(n=new WebSocket(i,c)).binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}var u={addr:t,port:r,socket:n,dgram_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,u),SOCKFS.websocket_sock_ops.handlePeerEvents(e,u),2===e.type&&void 0!==e.sport&&u.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),u},getPeer:(e,t,r)=>e.peers[t+":"+r],addPeer(e,t){e.peers[t.addr+":"+t.port]=t},removePeer(e,t){delete e.peers[t.addr+":"+t.port]},handlePeerEvents(e,t){var r=!0,n=function(){Module.websocket.emit("open",e.stream.fd);try{for(var r=t.dgram_send_queue.shift();r;)t.socket.send(r),r=t.dgram_send_queue.shift()}catch(e){t.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(assert(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=r;if(r=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var a=n[8]<<8|n[9];return SOCKFS.websocket_sock_ops.removePeer(e,t),t.port=a,void SOCKFS.websocket_sock_ops.addPeer(e,t)}e.recv_queue.push({addr:t.addr,port:t.port,data:n}),Module.websocket.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(t.socket.on("open",n),t.socket.on("message",function(e,t){t&&o(new Uint8Array(e).buffer)}),t.socket.on("close",function(){Module.websocket.emit("close",e.stream.fd)}),t.socket.on("error",function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(t.socket.onopen=n,t.socket.onclose=function(){Module.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){o(e.data)},t.socket.onerror=function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(1===e.type&&e.server)return e.pending.length?65:0;var t=0,r=1===e.type?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!r||r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=65),(!r||r&&r.socket.readyState===r.socket.OPEN)&&(t|=4),(r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=16),t},ioctl(e,t,r){if(21531===t){var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),HEAP32[r>>2]=n,0}return 28},close(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var t=Object.keys(e.peers),r=0;r{var t=SOCKFS.getSocket(e);if(!t)throw new FS.ErrnoError(8);return t},setErrNo=e=>(HEAP32[___errno_location()>>2]=e,e),inetNtop4=e=>(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var t="",r=0,n=0,o=0,a=0,i=0,s=0,l=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,u="";for(s=0;s<5;s++)if(0!==l[s]){c=!1;break}if(c){if(u=inetNtop4(l[6]|l[7]<<16),-1===l[5])return t="::ffff:",t+=u;if(0===l[5])return t="::","0.0.0.0"===u&&(u=""),"0.0.0.1"===u&&(u="1"),t+=u}for(r=0;r<8;r++)0===l[r]&&(r-o>1&&(i=0),o=r,i++),i>n&&(a=r-(n=i)+1);for(r=0;r<8;r++)n>1&&0===l[r]&&r>=a&&r{var r,n=HEAP16[e>>1],o=_ntohs(HEAPU16[e+2>>1]);switch(n){case 2:if(16!==t)return{errno:28};r=HEAP32[e+4>>2],r=inetNtop4(r);break;case 10:if(28!==t)return{errno:28};r=[HEAP32[e+8>>2],HEAP32[e+12>>2],HEAP32[e+16>>2],HEAP32[e+20>>2]],r=inetNtop6(r);break;default:return{errno:5}}return{family:n,addr:r,port:o}},inetPton4=e=>{for(var t=e.split("."),r=0;r<4;r++){var n=Number(t[r]);if(isNaN(n))return null;t[r]=n}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var t,r,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jstoi_q(t[t.length-4])+256*jstoi_q(t[t.length-3]),t[t.length-3]=jstoi_q(t[t.length-2])+256*jstoi_q(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),n=0,o=0,r=0;rDNS.address_map.names[e]?DNS.address_map.names[e]:null},getSocketAddress=(e,t,r)=>{if(r&&0===e)return null;var n=readSockaddr(e,t);if(n.errno)throw new FS.ErrnoError(n.errno);return n.addr=DNS.lookup_addr(n.addr)||n.addr,n};function ___syscall_connect(e,t,r,n,o,a){try{var i=getSocketFromFD(e),s=getSocketAddress(t,r);return i.sock_ops.connect(i,s.addr,s.port),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_faccessat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),-8&r)return-28;var o=FS.lookupPath(t,{follow:!0}).node;if(!o)return-44;var a="";return 4&r&&(a+="r"),2&r&&(a+="w"),1&r&&(a+="x"),a&&FS.nodePermissions(o,a)?-2:0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fcntl64(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 0:if((o=SYSCALLS.get())<0)return-28;for(;FS.streams[o];)o++;return FS.createStream(n,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return n.flags;case 4:var o=SYSCALLS.get();return n.flags|=o,0;case 5:o=SYSCALLS.getp();return HEAP16[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return setErrNo(28),-1}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fstat64(e,t){try{var r=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,r.path,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_ioctl(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return n.tty?0:-59;case 21505:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var o=n.tty.ops.ioctl_tcgets(n),a=SYSCALLS.getp();HEAP32[a>>2]=o.c_iflag||0,HEAP32[a+4>>2]=o.c_oflag||0,HEAP32[a+8>>2]=o.c_cflag||0,HEAP32[a+12>>2]=o.c_lflag||0;for(var i=0;i<32;i++)HEAP8[a+i+17|0]=o.c_cc[i]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){a=SYSCALLS.getp();var s=HEAP32[a>>2],l=HEAP32[a+4>>2],c=HEAP32[a+8>>2],u=HEAP32[a+12>>2],m=[];for(i=0;i<32;i++)m.push(HEAP8[a+i+17|0]);return n.tty.ops.ioctl_tcsets(n.tty,t,{c_iflag:s,c_oflag:l,c_cflag:c,c_lflag:u,c_cc:m})}return 0;case 21519:if(!n.tty)return-59;a=SYSCALLS.getp();return HEAP32[a>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:a=SYSCALLS.getp();return FS.ioctl(n,t,a);case 21523:if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var d=n.tty.ops.ioctl_tiocgwinsz(n.tty);a=SYSCALLS.getp();HEAP16[a>>1]=d[0],HEAP16[a+2>>1]=d[1]}return 0;default:return-28}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_mkdirat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),"/"===(t=PATH.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),FS.mkdir(t,r,0),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_newfstatat(e,t,r,n){try{t=SYSCALLS.getStr(t);var o=256&n,a=4096&n;return n&=-6401,t=SYSCALLS.calculateAt(e,t,a),SYSCALLS.doStat(o?FS.lstat:FS.stat,t,r)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_openat(e,t,r,n){SYSCALLS.varargs=n;try{t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t);var o=n?SYSCALLS.get():0;return FS.open(t,r,o).fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var stringToUTF8=(e,t,r)=>stringToUTF8Array(e,HEAPU8,t,r);function ___syscall_readlinkat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),n<=0)return-28;var o=FS.readlink(t),a=Math.min(n,lengthBytesUTF8(o)),i=HEAP8[r+a];return stringToUTF8(o,r,n+1),HEAP8[r+a]=i,a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_rmdir(e){try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_socket(e,t,r){try{return SOCKFS.createSocket(e,t,r).stream.fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_stat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_unlinkat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),0===r?FS.unlink(t):512===r?FS.rmdir(t):abort("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var nowIsMonotonic=!0,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic,convertI32PairToI53Checked=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN;function __gmtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getUTCSeconds(),HEAP32[r+4>>2]=o.getUTCMinutes(),HEAP32[r+8>>2]=o.getUTCHours(),HEAP32[r+12>>2]=o.getUTCDate(),HEAP32[r+16>>2]=o.getUTCMonth(),HEAP32[r+20>>2]=o.getUTCFullYear()-1900,HEAP32[r+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),i=(o.getTime()-a)/864e5|0;HEAP32[r+28>>2]=i}var isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>(isLeapYear(e.getFullYear())?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()]+e.getDate()-1;function __localtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getSeconds(),HEAP32[r+4>>2]=o.getMinutes(),HEAP32[r+8>>2]=o.getHours(),HEAP32[r+12>>2]=o.getDate(),HEAP32[r+16>>2]=o.getMonth(),HEAP32[r+20>>2]=o.getFullYear()-1900,HEAP32[r+24>>2]=o.getDay();var a=0|ydayFromDate(o);HEAP32[r+28>>2]=a,HEAP32[r+36>>2]=-60*o.getTimezoneOffset();var i=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),l=i.getTimezoneOffset(),c=0|(s!=l&&o.getTimezoneOffset()==Math.min(l,s));HEAP32[r+32>>2]=c}var _emscripten_get_now,stringToNewUTF8=e=>{var t=lengthBytesUTF8(e)+1,r=_malloc(t);return r&&stringToUTF8(e,r,t),r},__tzset_js=(e,t,r)=>{var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),i=o.getTimezoneOffset(),s=a.getTimezoneOffset(),l=Math.max(i,s);function c(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}HEAPU32[e>>2]=60*l,HEAP32[t>>2]=Number(i!=s);var u=c(o),m=c(a),d=stringToNewUTF8(u),_=stringToNewUTF8(m);s>2]=d,HEAPU32[r+4>>2]=_):(HEAPU32[r>>2]=_,HEAPU32[r+4>>2]=d)},_abort=()=>{abort("")},_emscripten_date_now=()=>Date.now(),getHeapMax=()=>2147483648,_emscripten_get_heap_max=()=>getHeapMax();_emscripten_get_now=()=>performance.now();var reallyNegative=e=>e<0||0===e&&1/e==-1/0,convertI32PairToI53=(e,t)=>(e>>>0)+4294967296*t,convertU32PairToI53=(e,t)=>(e>>>0)+4294967296*(t>>>0),reSign=(e,t)=>{if(e<=0)return e;var r=t<=32?Math.abs(1<=r&&(t<=32||e>r)&&(e=-2*r+e),e},unSign=(e,t)=>e>=0?e:t<=32?2*Math.abs(1<{for(var t=e;HEAPU8[t];)++t;return t-e},formatString=(e,t)=>{var r=e,n=t;function o(e){var t;return n=function(e,t){return"double"!==t&&"i64"!==t||7&e&&(e+=4),e}(n,e),"double"===e?(t=HEAPF64[n>>3],n+=8):"i64"==e?(t=[HEAP32[n>>2],HEAP32[n+4>>2]],n+=8):(e="i32",t=HEAP32[n>>2],n+=4),t}for(var a,i,s,l=[];;){var c=r;if(0===(a=HEAP8[r|0]))break;if(i=HEAP8[r+1|0],37==a){var u=!1,m=!1,d=!1,_=!1,f=!1;e:for(;;){switch(i){case 43:u=!0;break;case 45:m=!0;break;case 35:d=!0;break;case 48:if(_)break e;_=!0;break;case 32:f=!0;break;default:break e}r++,i=HEAP8[r+1|0]}var g=0;if(42==i)g=o("i32"),r++,i=HEAP8[r+1|0];else for(;i>=48&&i<=57;)g=10*g+(i-48),r++,i=HEAP8[r+1|0];var p,S=!1,h=-1;if(46==i){if(h=0,S=!0,r++,42==(i=HEAP8[r+1|0]))h=o("i32"),r++;else for(;;){var E=HEAP8[r+1|0];if(E<48||E>57)break;h=10*h+(E-48),r++}i=HEAP8[r+1|0]}switch(h<0&&(h=6,S=!1),String.fromCharCode(i)){case"h":104==HEAP8[r+2|0]?(r++,p=1):p=2;break;case"l":108==HEAP8[r+2|0]?(r++,p=8):p=4;break;case"L":case"q":case"j":p=8;break;case"z":case"t":case"I":p=4;break;default:p=null}switch(p&&r++,i=HEAP8[r+1|0],String.fromCharCode(i)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":var v=100==i||105==i;if(s=o("i"+8*(p=p||4)),8==p&&(s=117==i?convertU32PairToI53(s[0],s[1]):convertI32PairToI53(s[0],s[1])),p<=4){var F=Math.pow(256,p)-1;s=(v?reSign:unSign)(s&F,8*p)}var y=Math.abs(s),w="";if(100==i||105==i)k=reSign(s,8*p).toString(10);else if(117==i)k=unSign(s,8*p).toString(10),s=Math.abs(s);else if(111==i)k=(d?"0":"")+y.toString(8);else if(120==i||88==i){if(w=d&&0!=s?"0x":"",s<0){s=-s,k=(y-1).toString(16);for(var D=[],b=0;b=0&&(u?w="+"+w:f&&(w=" "+w)),"-"==k.charAt(0)&&(w="-"+w,k=k.substr(1));w.length+k.lengthT&&T>=-4?(i=(103==i?"f":"F").charCodeAt(0),h-=T+1):(i=(103==i?"e":"E").charCodeAt(0),h--),R=Math.min(h,20)}101==i||69==i?(k=s.toExponential(R),/[eE][-+]\d$/.test(k)&&(k=k.slice(0,-1)+"0"+k.slice(-1))):102!=i&&70!=i||(k=s.toFixed(R),0===s&&reallyNegative(s)&&(k="-"+k));var C=k.split("e");if(N&&!d)for(;C[0].length>1&&C[0].includes(".")&&("0"==C[0].slice(-1)||"."==C[0].slice(-1));)C[0]=C[0].slice(0,-1);else for(d&&-1==k.indexOf(".")&&(C[0]+=".");h>R++;)C[0]+="0";k=C[0]+(C.length>1?"e"+C[1]:""),69==i&&(k=k.toUpperCase()),s>=0&&(u?k="+"+k:f&&(k=" "+k))}else k=(s<0?"-":"")+"inf",_=!1;for(;k.length0;)l.push(32);m||l.push(o("i8"));break;case"n":var M=o("i32*");HEAP32[M>>2]=l.length;break;case"%":l.push(a);break;default:for(b=c;b{warnOnce.shown||(warnOnce.shown={}),warnOnce.shown[e]||(warnOnce.shown[e]=1,err(e))};function getCallstack(e){var t=jsStackTrace(),r=t.lastIndexOf("_emscripten_log"),n=t.lastIndexOf("_emscripten_get_callstack"),o=t.indexOf("\n",Math.max(r,n))+1;t=t.slice(o),8&e&&"undefined"==typeof emscripten_source_map&&(warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'),e^=8,e|=16);var a=t.split("\n");t="";var i=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"),s=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"),l=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var c in a){var u=a[c],m="",d="",_=0,f=0,g=l.exec(u);if(g&&5==g.length)m=g[1],d=g[2],_=g[3],f=g[4];else{if((g=i.exec(u))||(g=s.exec(u)),!(g&&g.length>=4)){t+=u+"\n";continue}m=g[1],d=g[2],_=g[3],f=0|g[4]}var p=!1;if(8&e){var S=emscripten_source_map.originalPositionFor({line:_,column:f});(p=S&&S.source)&&(64&e&&(S.source=S.source.substring(S.source.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=` at ${m} (${S.source}:${S.line}:${S.column})\n`)}(16&e||!p)&&(64&e&&(d=d.substring(d.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=(p?` = ${m}`:` at ${m}`)+` (${d}:${_}:${f})\n`)}return t=t.replace(/\s+$/,"")}var emscriptenLog=(e,t)=>{24&e&&(t=t.replace(/\s+$/,""),t+=(t.length>0?"\n":"")+getCallstack(e)),1&e?4&e||2&e?err(t):out(t):6&e?err(t):out(t)},_emscripten_log=(e,t,r)=>{var n=formatString(t,r),o=UTF8ArrayToString(n,0);emscriptenLog(e,o)},growMemory=e=>{var t=(e-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch(e){}},_emscripten_resize_heap=e=>{var t=HEAPU8.length;e>>>=0;var r=getHeapMax();if(e>r)return!1;for(var n=(e,t)=>e+(t-e%t)%t,o=1;o<=4;o*=2){var a=t*(1+.2/o);a=Math.min(a,e+100663296);var i=Math.min(r,n(Math.max(e,a),65536));if(growMemory(i))return!0}return!1},ENV={},getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(var t in ENV)void 0===ENV[t]?delete e[t]:e[t]=ENV[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToAscii=(e,t)=>{for(var r=0;r{var r=0;return getEnvStrings().forEach((n,o)=>{var a=t+r;HEAPU32[e+4*o>>2]=a,stringToAscii(n,a),r+=n.length+1}),0},_environ_sizes_get=(e,t)=>{var r=getEnvStrings();HEAPU32[e>>2]=r.length;var n=0;return r.forEach(e=>n+=e.length+1),HEAPU32[t>>2]=n,0};function _fd_close(e){try{var t=SYSCALLS.getStreamFromFD(e);return FS.close(t),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doReadv=(e,t,r,n)=>{for(var o=0,a=0;a>2],s=HEAPU32[t+4>>2];t+=8;var l=FS.read(e,HEAP8,i,s,n);if(l<0)return-1;if(o+=l,l>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}function _fd_seek(e,t,r,n,o){var a=convertI32PairToI53Checked(t,r);try{if(isNaN(a))return 61;var i=SYSCALLS.getStreamFromFD(e);return FS.llseek(i,a,n),tempI64=[i.position>>>0,(tempDouble=i.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[o>>2]=tempI64[0],HEAP32[o+4>>2]=tempI64[1],i.getdents&&0===a&&0===n&&(i.getdents=null),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doWritev=(e,t,r,n)=>{for(var o=0,a=0;a>2],s=HEAPU32[t+4>>2];t+=8;var l=FS.write(e,HEAP8,i,s,n);if(l<0)return-1;o+=l,void 0!==n&&(n+=l)}return o};function _fd_write(e,t,r,n){try{var o=SYSCALLS.getStreamFromFD(e),a=doWritev(o,t,r);return HEAPU32[n>>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var wasmTable,functionsInTableMap,arraySum=(e,t)=>{for(var r=0,n=0;n<=t;r+=e[n++]);return r},MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31],MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31],addDays=(e,t)=>{for(var r=new Date(e.getTime());t>0;){var n=isLeapYear(r.getFullYear()),o=r.getMonth(),a=(n?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[o];if(!(t>a-r.getDate()))return r.setDate(r.getDate()+t),r;t-=a-r.getDate()+1,r.setDate(1),o<11?r.setMonth(o+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r},writeArrayToMemory=(e,t)=>{HEAP8.set(e,t)},_strftime=(e,t,r,n)=>{var o=HEAPU32[n+40>>2],a={tm_sec:HEAP32[n>>2],tm_min:HEAP32[n+4>>2],tm_hour:HEAP32[n+8>>2],tm_mday:HEAP32[n+12>>2],tm_mon:HEAP32[n+16>>2],tm_year:HEAP32[n+20>>2],tm_wday:HEAP32[n+24>>2],tm_yday:HEAP32[n+28>>2],tm_isdst:HEAP32[n+32>>2],tm_gmtoff:HEAP32[n+36>>2],tm_zone:o?UTF8ToString(o):""},i=UTF8ToString(r),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in s)i=i.replace(new RegExp(l,"g"),s[l]);var c=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"];function m(e,t,r){for(var n="number"==typeof e?e.toString():e||"";n.length0?1:0}var n;return 0===(n=r(e.getFullYear()-t.getFullYear()))&&0===(n=r(e.getMonth()-t.getMonth()))&&(n=r(e.getDate()-t.getDate())),n}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function g(e){var t=addDays(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),n=new Date(t.getFullYear()+1,0,4),o=f(r),a=f(n);return _(o,t)<=0?_(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var p={"%a":e=>c[e.tm_wday].substring(0,3),"%A":e=>c[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>d((e.tm_year+1900)/100|0,2),"%d":e=>d(e.tm_mday,2),"%e":e=>m(e.tm_mday,2," "),"%g":e=>g(e).toString().substring(2),"%G":e=>g(e),"%H":e=>d(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":e=>d(e.tm_mday+arraySum(isLeapYear(e.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,e.tm_mon-1),3),"%m":e=>d(e.tm_mon+1,2),"%M":e=>d(e.tm_min,2),"%n":()=>"\n","%p":e=>e.tm_hour>=0&&e.tm_hour<12?"AM":"PM","%S":e=>d(e.tm_sec,2),"%t":()=>"\t","%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&isLeapYear(e.tm_year)||(t=1)}}else{t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(4==n||5==n&&isLeapYear(e.tm_year%400-1))&&t++}return d(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>"%"};for(var l in i=i.replace(/%%/g,"\0\0"),p)i.includes(l)&&(i=i.replace(new RegExp(l,"g"),p[l](a)));var S=intArrayFromString(i=i.replace(/\0\0/g,"%"),!1);return S.length>t?0:(writeArrayToMemory(S,e),S.length-1)},_strftime_l=(e,t,r,n,o)=>_strftime(e,t,r,n),getWasmTableEntry=e=>wasmTable.get(e),uleb128Encode=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var t={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"},r={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},n=1;n{var r=e.slice(0,1),n=e.slice(1),o={i:127,p:127,j:126,f:125,d:124};t.push(96),uleb128Encode(n.length,t);for(var a=0;a{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function(sigToWasmTypes(t),e);var r=[1];generateFuncType(t,r);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(r.length,n),n.push.apply(n,r),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var o=new WebAssembly.Module(new Uint8Array(n));return new WebAssembly.Instance(o,{e:{f:e}}).exports.f},updateTableMap=(e,t)=>{if(functionsInTableMap)for(var r=e;r(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1},setWasmTableEntry=(e,t)=>wasmTable.set(e,t),addFunction=(e,t)=>{var r=getFunctionAddress(e);if(r)return r;var n=getEmptyTableSlot();try{setWasmTableEntry(n,e)}catch(r){if(!(r instanceof TypeError))throw r;var o=convertJsFunctionToWasm(e,t);setWasmTableEntry(n,o)}return functionsInTableMap.set(e,n),n},stringToUTF8OnStack=e=>{var t=lengthBytesUTF8(e)+1,r=stackAlloc(t);return stringToUTF8(e,r,t),r},FSNode=function(e,t,r,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=FS.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n},readMode=365,writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(e){e?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(e){e?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}}),FS.FSNode=FSNode,FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit();var calledRun,wasmImports={CreateDirectoryFetcher:_CreateDirectoryFetcher,DDN_ConvertElement:_DDN_ConvertElement,DDN_CreateDDNResult:_DDN_CreateDDNResult,DDN_CreateDDNResultItem:_DDN_CreateDDNResultItem,DDN_CreateIntermediateResultUnits:_DDN_CreateIntermediateResultUnits,DDN_CreateParameters:_DDN_CreateParameters,DDN_CreateTargetRoiDefConditionFilter:_DDN_CreateTargetRoiDefConditionFilter,DDN_CreateTaskAlgEntity:_DDN_CreateTaskAlgEntity,DDN_HasSection:_DDN_HasSection,DDN_ReadTaskSetting:_DDN_ReadTaskSetting,DLR_ConvertElement:_DLR_ConvertElement,DLR_CreateBufferedCharacterItemSet:_DLR_CreateBufferedCharacterItemSet,DLR_CreateIntermediateResultUnits:_DLR_CreateIntermediateResultUnits,DLR_CreateParameters:_DLR_CreateParameters,DLR_CreateRecognizedTextLinesResult:_DLR_CreateRecognizedTextLinesResult,DLR_CreateTargetRoiDefConditionFilter:_DLR_CreateTargetRoiDefConditionFilter,DLR_CreateTaskAlgEntity:_DLR_CreateTaskAlgEntity,DLR_CreateTextLineResultItem:_DLR_CreateTextLineResultItem,DLR_ReadTaskSetting:_DLR_ReadTaskSetting,DMImage_GetDIB:_DMImage_GetDIB,DMImage_GetOrientation:_DMImage_GetOrientation,DNN_CreateSession:_DNN_CreateSession,DNN_GetRegionByIndex:_DNN_GetRegionByIndex,DNN_ReleaseRegion:_DNN_ReleaseRegion,DNN_ReleaseSession:_DNN_ReleaseSession,DNN_RunDeblurInference:_DNN_RunDeblurInference,DNN_RunDeblurInference_C1:_DNN_RunDeblurInference_C1,DNN_RunLocalizationInference:_DNN_RunLocalizationInference,DeleteDirectoryFetcher:_DeleteDirectoryFetcher,_ZN19LabelRecognizerWasm10getVersionEv:__ZN19LabelRecognizerWasm10getVersionEv,_ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv:__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv,_ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv:__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv,_ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi:__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi,_ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb:__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb,_ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb:__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb,_ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb:__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb,_ZN19LabelRecognizerWasm12DlrWasmClassC1Ev:__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev,_ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE:__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE,_ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE:__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE,_ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE:__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE,_ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE:__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE,_ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE:__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE,_ZN22DocumentNormalizerWasm10getVersionEv:__ZN22DocumentNormalizerWasm10getVersionEv,_ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv:__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv,_ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi:__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi,_ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii:__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii,_ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE,_ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev:__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev,_ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE:__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE,_ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE:__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE,_ZN9dynamsoft7utility14CUtilityModule10GetVersionEv:__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv,__assert_fail:___assert_fail,__cxa_begin_catch:___cxa_begin_catch,__cxa_end_catch:___cxa_end_catch,__cxa_find_matching_catch_2:___cxa_find_matching_catch_2,__cxa_find_matching_catch_3:___cxa_find_matching_catch_3,__cxa_rethrow:___cxa_rethrow,__cxa_rethrow_primary_exception:___cxa_rethrow_primary_exception,__cxa_throw:___cxa_throw,__cxa_uncaught_exceptions:___cxa_uncaught_exceptions,__resumeException:___resumeException,__syscall__newselect:___syscall__newselect,__syscall_connect:___syscall_connect,__syscall_faccessat:___syscall_faccessat,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_ioctl:___syscall_ioctl,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_readlinkat:___syscall_readlinkat,__syscall_rmdir:___syscall_rmdir,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_unlinkat:___syscall_unlinkat,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_tzset_js:__tzset_js,abort:_abort,emscripten_date_now:_emscripten_date_now,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_log:_emscripten_log,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,invoke_diii:invoke_diii,invoke_fiii:invoke_fiii,invoke_i:invoke_i,invoke_ii:invoke_ii,invoke_iii:invoke_iii,invoke_iiii:invoke_iiii,invoke_iiiii:invoke_iiiii,invoke_iiiiid:invoke_iiiiid,invoke_iiiiii:invoke_iiiiii,invoke_iiiiiii:invoke_iiiiiii,invoke_iiiiiiii:invoke_iiiiiiii,invoke_iiiiiiiiiiii:invoke_iiiiiiiiiiii,invoke_iiiiij:invoke_iiiiij,invoke_j:invoke_j,invoke_ji:invoke_ji,invoke_jii:invoke_jii,invoke_jiiii:invoke_jiiii,invoke_v:invoke_v,invoke_vi:invoke_vi,invoke_vii:invoke_vii,invoke_viid:invoke_viid,invoke_viii:invoke_viii,invoke_viiii:invoke_viiii,invoke_viiiiiii:invoke_viiiiiii,invoke_viiiiiiiiii:invoke_viiiiiiiiii,invoke_viiiiiiiiiiiiiii:invoke_viiiiiiiiiiiiiii,strftime:_strftime,strftime_l:_strftime_l},wasmExports=createWasm();function invoke_iiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(e,t){var r=stackSave();try{return getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(e,t,r){var n=stackSave();try{return getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(e,t,r){var n=stackSave();try{getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(e,t,r,n,o){var a=stackSave();try{getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(e){var t=stackSave();try{getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(e,t,r,n,o){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(e,t){var r=stackSave();try{getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(e,t,r,n,o,a){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(e,t,r,n,o,a,i){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,i)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiid(e,t,r,n,o,a){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiii(e,t,r,n,o,a,i,s){var l=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,i,s)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_diii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(e){var t=stackSave();try{return getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(e,t,r,n,o,a,i,s){var l=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,i,s)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(e,t,r,n,o,a,i,s,l,c,u,m){var d=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,i,s,l,c,u,m)}catch(e){if(stackRestore(d),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(e,t,r,n,o,a,i,s,l,c,u){var m=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,i,s,l,c,u)}catch(e){if(stackRestore(m),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(e,t,r,n,o,a,i,s,l,c,u,m,d,_,f,g){var p=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,i,s,l,c,u,m,d,_,f,g)}catch(e){if(stackRestore(p),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_j(e){var t=stackSave();try{return dynCall_j(e)}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(e,t){var r=stackSave();try{return dynCall_ji(e,t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(e,t,r){var n=stackSave();try{return dynCall_jii(e,t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiij(e,t,r,n,o,a,i){var s=stackSave();try{return dynCall_iiiiij(e,t,r,n,o,a,i)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(e,t,r,n,o){var a=stackSave();try{return dynCall_jiiii(e,t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function run(){function e(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT||(initRuntime(),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)]()[UTF8ToString(r)]()),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack((new(self[UTF8ToString(e)]))[UTF8ToString(t)](UTF8ToString(r))),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>{self[UTF8ToString(e)](null,UTF8ToString(t).trim(),UTF8ToString(r),n)},"viiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)][UTF8ToString(r)](UTF8ToString(n))?"":self[UTF8ToString(e)][UTF8ToString(t)]),"iiiii")),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun()))}runDependencies>0||(preRun(),runDependencies>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()))}if(Module.addFunction=addFunction,Module.stringToUTF8OnStack=stringToUTF8OnStack,dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)},Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();run(); \ No newline at end of file +var read_,readAsync,readBinary,Module=void 0!==Module?Module:{},moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(e,t)=>{throw t},ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!0,ENVIRONMENT_IS_NODE=!1,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:"undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=0!==scriptDirectory.indexOf("blob:")?scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1):"",read_=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var t=new XMLHttpRequest;t.open("GET",e,!1),t.responseType="arraybuffer";let r=Date.now();return t.onloadstart=()=>{postMessage({type:"event",id:-3,body:{loaded:0,total:pe.lengthComputable?pe.total:0,tag:"starting",resourcesPath:e}})},t.onprogress=t=>{const n=Date.now();r+500{postMessage({type:"event",id:-3,body:{loaded:pe.lengthComputable?pe.total:0,total:pe.lengthComputable?pe.total:0,tag:"completed",resourcesPath:e}})},t.send(null),new Uint8Array(t.response)}),readAsync=(e,t,r)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=()=>{200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var wasmBinary,out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit),Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,noExitRuntime=Module.noExitRuntime||!0;"object"!=typeof WebAssembly&&abort("no native wasm support detected");var EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,ABORT=!1;function assert(e,t){e||abort(t)}function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e)}var __ATPRERUN__=[],__ATINIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,Module.noFSInit||FS.init.initialized||FS.init(),FS.ignorePermissions=!1,TTY.init(),SOCKFS.root=FS.mount(SOCKFS,{},null),callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module.postRun)for("function"==typeof Module.postRun&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(e){return e}function addRunDependency(e){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}function removeRunDependency(e){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}}function abort(e){throw Module.onAbort&&Module.onAbort(e),err(e="Aborted("+e+")"),ABORT=!0,EXITSTATUS=1,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}var wasmBinaryFile,tempDouble,tempI64,dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(e){return e.startsWith(dataURIPrefix)}function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(e){return wasmBinary||!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER||"function"!=typeof fetch?Promise.resolve().then(()=>getBinarySync(e)):fetch(e,{credentials:"same-origin"}).then(async t=>{if(!t.ok)throw"failed to load wasm binary file at '"+e+"'";postMessage({type:"event",id:-3,body:{total:0,loaded:0,tag:"starting",resourcesPath:e}});const r=+t.headers.get("Content-Length"),n=t.body.getReader();let o=0,a=Date.now();const s=[];for(;;){const{done:t,value:i}=await n.read();if(t)break;if(s.push(i),o+=i.length,r){const t=Date.now();a+500getBinarySync(e))}function instantiateArrayBuffer(e,t,r){return getBinaryPromise(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(r,e=>{err(`failed to asynchronously prepare wasm: ${e}`),abort(e)})}function instantiateAsync(e,t,r,n){return instantiateArrayBuffer(t,r,n)}function createWasm(){var e={env:wasmImports,wasi_snapshot_preview1:wasmImports};function t(e,t){return wasmExports=e.exports,wasmMemory=wasmExports.memory,updateMemoryViews(),wasmTable=wasmExports.__indirect_function_table,addOnInit(wasmExports.__wasm_call_ctors),exportWasmSymbols(wasmExports),removeRunDependency("wasm-instantiate"),wasmExports}if(addRunDependency("wasm-instantiate"),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return err(`Module.instantiateWasm callback failed with error: ${e}`),!1}return instantiateAsync(wasmBinary,wasmBinaryFile,e,function(e){t(e.instance)}),{}}isDataURI(wasmBinaryFile="dynamsoft-barcode-reader-bundle.wasm")||(wasmBinaryFile=locateFile(wasmBinaryFile));var callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},asmjsMangle=e=>("__main_argc_argv"==e&&(e="main"),0==e.indexOf("dynCall_")||["stackAlloc","stackSave","stackRestore","getTempRet0","setTempRet0"].includes(e)?e:"_"+e),exportWasmSymbols=e=>{for(var t in e){var r=asmjsMangle(t);this[r]=Module[r]=e[t]}};function _CreateDirectoryFetcher(){abort("missing function: CreateDirectoryFetcher")}function _DDN_ConvertElement(){abort("missing function: DDN_ConvertElement")}function _DDN_CreateDDNResult(){abort("missing function: DDN_CreateDDNResult")}function _DDN_CreateDDNResultItem(){abort("missing function: DDN_CreateDDNResultItem")}function _DDN_CreateIntermediateResultUnits(){abort("missing function: DDN_CreateIntermediateResultUnits")}function _DDN_CreateParameters(){abort("missing function: DDN_CreateParameters")}function _DDN_CreateTargetRoiDefConditionFilter(){abort("missing function: DDN_CreateTargetRoiDefConditionFilter")}function _DDN_CreateTaskAlgEntity(){abort("missing function: DDN_CreateTaskAlgEntity")}function _DDN_HasSection(){abort("missing function: DDN_HasSection")}function _DDN_ReadTaskSetting(){abort("missing function: DDN_ReadTaskSetting")}function _DLR_ConvertElement(){abort("missing function: DLR_ConvertElement")}function _DLR_CreateBufferedCharacterItemSet(){abort("missing function: DLR_CreateBufferedCharacterItemSet")}function _DLR_CreateIntermediateResultUnits(){abort("missing function: DLR_CreateIntermediateResultUnits")}function _DLR_CreateParameters(){abort("missing function: DLR_CreateParameters")}function _DLR_CreateRecognizedTextLinesResult(){abort("missing function: DLR_CreateRecognizedTextLinesResult")}function _DLR_CreateTargetRoiDefConditionFilter(){abort("missing function: DLR_CreateTargetRoiDefConditionFilter")}function _DLR_CreateTaskAlgEntity(){abort("missing function: DLR_CreateTaskAlgEntity")}function _DLR_CreateTextLineResultItem(){abort("missing function: DLR_CreateTextLineResultItem")}function _DLR_ReadTaskSetting(){abort("missing function: DLR_ReadTaskSetting")}function _DMImage_GetDIB(){abort("missing function: DMImage_GetDIB")}function _DMImage_GetOrientation(){abort("missing function: DMImage_GetOrientation")}function _DeleteDirectoryFetcher(){abort("missing function: DeleteDirectoryFetcher")}function __ZN19LabelRecognizerWasm10getVersionEv(){abort("missing function: _ZN19LabelRecognizerWasm10getVersionEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv")}function __ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi")}function __ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb")}function __ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb")}function __ZN19LabelRecognizerWasm12DlrWasmClassC1Ev(){abort("missing function: _ZN19LabelRecognizerWasm12DlrWasmClassC1Ev")}function __ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE(){abort("missing function: _ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE")}function __ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE(){abort("missing function: _ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE")}function __ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE")}function __ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE(){abort("missing function: _ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE")}function __ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE(){abort("missing function: _ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE")}function __ZN22DocumentNormalizerWasm10getVersionEv(){abort("missing function: _ZN22DocumentNormalizerWasm10getVersionEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi")}function __ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii")}function __ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib")}function __ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb")}function __ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE")}function __ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev(){abort("missing function: _ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev")}function __ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE")}function __ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE(){abort("missing function: _ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE")}function __ZN9dynamsoft7utility14CUtilityModule10GetVersionEv(){abort("missing function: _ZN9dynamsoft7utility14CUtilityModule10GetVersionEv")}_CreateDirectoryFetcher.stub=!0,_DDN_ConvertElement.stub=!0,_DDN_CreateDDNResult.stub=!0,_DDN_CreateDDNResultItem.stub=!0,_DDN_CreateIntermediateResultUnits.stub=!0,_DDN_CreateParameters.stub=!0,_DDN_CreateTargetRoiDefConditionFilter.stub=!0,_DDN_CreateTaskAlgEntity.stub=!0,_DDN_HasSection.stub=!0,_DDN_ReadTaskSetting.stub=!0,_DLR_ConvertElement.stub=!0,_DLR_CreateBufferedCharacterItemSet.stub=!0,_DLR_CreateIntermediateResultUnits.stub=!0,_DLR_CreateParameters.stub=!0,_DLR_CreateRecognizedTextLinesResult.stub=!0,_DLR_CreateTargetRoiDefConditionFilter.stub=!0,_DLR_CreateTaskAlgEntity.stub=!0,_DLR_CreateTextLineResultItem.stub=!0,_DLR_ReadTaskSetting.stub=!0,_DMImage_GetDIB.stub=!0,_DMImage_GetOrientation.stub=!0,_DeleteDirectoryFetcher.stub=!0,__ZN19LabelRecognizerWasm10getVersionEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb.stub=!0,__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev.stub=!0,__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE.stub=!0,__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE.stub=!0,__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE.stub=!0,__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE.stub=!0,__ZN22DocumentNormalizerWasm10getVersionEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE.stub=!0,__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev.stub=!0,__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE.stub=!0,__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE.stub=!0,__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv.stub=!0;var UTF8Decoder="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,UTF8ArrayToString=(e,t,r)=>{for(var n=t+r,o=t;e[o]&&!(o>=n);)++o;if(o-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,o));for(var a="";t>10,56320|1023&c)}}else a+=String.fromCharCode((31&s)<<6|i)}else a+=String.fromCharCode(s)}return a},UTF8ToString=(e,t)=>e?UTF8ArrayToString(HEAPU8,e,t):"",___assert_fail=(e,t,r,n)=>{abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[t?UTF8ToString(t):"unknown filename",r,n?UTF8ToString(n):"unknown function"])},exceptionCaught=[],uncaughtExceptionCount=0,___cxa_begin_catch=e=>{var t=new ExceptionInfo(e);return t.get_caught()||(t.set_caught(!0),uncaughtExceptionCount--),t.set_rethrown(!1),exceptionCaught.push(t),___cxa_increment_exception_refcount(t.excPtr),t.get_exception_ptr()},exceptionLast=0,___cxa_end_catch=()=>{_setThrew(0,0);var e=exceptionCaught.pop();___cxa_decrement_exception_refcount(e.excPtr),exceptionLast=0};function ExceptionInfo(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){HEAPU32[this.ptr+4>>2]=e},this.get_type=function(){return HEAPU32[this.ptr+4>>2]},this.set_destructor=function(e){HEAPU32[this.ptr+8>>2]=e},this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]},this.set_caught=function(e){e=e?1:0,HEAP8[this.ptr+12|0]=e},this.get_caught=function(){return 0!=HEAP8[this.ptr+12|0]},this.set_rethrown=function(e){e=e?1:0,HEAP8[this.ptr+13|0]=e},this.get_rethrown=function(){return 0!=HEAP8[this.ptr+13|0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t)},this.set_adjusted_ptr=function(e){HEAPU32[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]},this.get_exception_ptr=function(){if(___cxa_is_pointer_type(this.get_type()))return HEAPU32[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var ___resumeException=e=>{throw exceptionLast||(exceptionLast=e),exceptionLast},findMatchingCatch=e=>{var t=exceptionLast;if(!t)return setTempRet0(0),0;var r=new ExceptionInfo(t);r.set_adjusted_ptr(t);var n=r.get_type();if(!n)return setTempRet0(0),t;for(var o in e){var a=e[o];if(0===a||a===n)break;var s=r.ptr+16;if(___cxa_can_catch(a,n,s))return setTempRet0(a),t}return setTempRet0(n),t},___cxa_find_matching_catch_2=()=>findMatchingCatch([]),___cxa_find_matching_catch_3=e=>findMatchingCatch([e]),___cxa_rethrow=()=>{var e=exceptionCaught.pop();e||abort("no exception to throw");var t=e.excPtr;throw e.get_rethrown()||(exceptionCaught.push(e),e.set_rethrown(!0),e.set_caught(!1),uncaughtExceptionCount++),exceptionLast=t},___cxa_rethrow_primary_exception=e=>{if(e){var t=new ExceptionInfo(e);exceptionCaught.push(t),t.set_rethrown(!0),___cxa_rethrow()}},___cxa_throw=(e,t,r)=>{throw new ExceptionInfo(e).init(t,r),uncaughtExceptionCount++,exceptionLast=e},___cxa_uncaught_exceptions=()=>uncaughtExceptionCount,PATH={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=PATH.isAbs(e),r="/"===e.substr(-1);return(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=PATH.splitPath(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=PATH.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return PATH.normalize(e.join("/"))},join2:(e,t)=>PATH.normalize(e+"/"+t)},initRandomFill=()=>{if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues)return e=>crypto.getRandomValues(e);abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:FS.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,t=PATH.isAbs(n)}return(t?"/":"")+(e=PATH.normalizeArray(e.split("/").filter(e=>!!e),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=PATH_FS.resolve(e).substr(1),t=PATH_FS.resolve(t).substr(1);for(var n=r(e.split("/")),o=r(t.split("/")),a=Math.min(n.length,o.length),s=a,i=0;i{for(var t=0,r=0;r=55296&&n<=57343?(t+=4,++r):t+=3}return t},stringToUTF8Array=(e,t,r,n)=>{if(!(n>0))return 0;for(var o=r,a=r+n-1,s=0;s=55296&&i<=57343)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++s);if(i<=127){if(r>=a)break;t[r++]=i}else if(i<=2047){if(r+1>=a)break;t[r++]=192|i>>6,t[r++]=128|63&i}else if(i<=65535){if(r+2>=a)break;t[r++]=224|i>>12,t[r++]=128|i>>6&63,t[r++]=128|63&i}else{if(r+3>=a)break;t[r++]=240|i>>18,t[r++]=128|i>>12&63,t[r++]=128|i>>6&63,t[r++]=128|63&i}}return t[r]=0,r-o};function intArrayFromString(e,t,r){var n=r>0?r:lengthBytesUTF8(e)+1,o=new Array(n),a=stringToUTF8Array(e,o,0,o.length);return t&&(o.length=a),o}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(e=window.prompt("Input: "))&&(e+="\n"):"function"==typeof readline&&null!==(e=readline())&&(e+="\n"),!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,t){TTY.ttys[e]={input:[],output:[],ops:t},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var t=TTY.ttys[e.node.rdev];if(!t)throw new FS.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,r,n,o){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var a=0,s=0;sFS_stdin_getChar(),put_char(e,t){null===t||10===t?(out(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(out(UTF8ArrayToString(e.output,0)),e.output=[])},ioctl_tcgets:e=>({c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}),ioctl_tcsets:(e,t,r)=>0,ioctl_tiocgwinsz:e=>[24,80]},default_tty1_ops:{put_char(e,t){null===t||10===t?(err(UTF8ArrayToString(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output,0)),e.output=[])}}},mmapAlloc=e=>{abort()},MEMFS={ops_table:null,mount:e=>MEMFS.createNode(null,"/",16895,0),createNode(e,t,r,n){if(FS.isBlkdev(r)||FS.isFIFO(r))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var o=FS.createNode(e,t,r,n);return FS.isDir(o.mode)?(o.node_ops=MEMFS.ops_table.dir.node,o.stream_ops=MEMFS.ops_table.dir.stream,o.contents={}):FS.isFile(o.mode)?(o.node_ops=MEMFS.ops_table.file.node,o.stream_ops=MEMFS.ops_table.file.stream,o.usedBytes=0,o.contents=null):FS.isLink(o.mode)?(o.node_ops=MEMFS.ops_table.link.node,o.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(o.mode)&&(o.node_ops=MEMFS.ops_table.chrdev.node,o.stream_ops=MEMFS.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[t]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:e=>e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0),expandFileStorage(e,t){var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var n=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr(e){var t={};return t.dev=FS.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,FS.isDir(e.mode)?t.size=4096:FS.isFile(e.mode)?t.size=e.usedBytes:FS.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&MEMFS.resizeFileStorage(e,t.size)},lookup(e,t){throw FS.genericErrors[44]},mknod:(e,t,r,n)=>MEMFS.createNode(e,t,r,n),rename(e,t,r){if(FS.isDir(e.mode)){var n;try{n=FS.lookupNode(t,r)}catch(e){}if(n)for(var o in n.contents)throw new FS.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){var r=FS.lookupNode(e,t);for(var n in r.contents)throw new FS.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink(e,t,r){var n=MEMFS.createNode(e,t,41471,0);return n.link=r,n},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,t,r,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-o,n);if(s>8&&a.subarray)t.set(a.subarray(o,o+s),r);else for(var i=0;i0||r+t(MEMFS.stream_ops.write(e,t,0,n,r,!1),0)}},asyncLoad=(e,t,r,n)=>{var o=n?"":getUniqueRunDependency(`al ${e}`);readAsync(e,r=>{assert(r,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(r)),o&&removeRunDependency(o)},t=>{if(!r)throw`Loading data file "${e}" failed.`;r()}),o&&addRunDependency(o)},FS_createDataFile=(e,t,r,n,o,a)=>FS.createDataFile(e,t,r,n,o,a),preloadPlugins=Module.preloadPlugins||[],FS_handledByPreloadPlugin=(e,t,r,n)=>{"undefined"!=typeof Browser&&Browser.init();var o=!1;return preloadPlugins.forEach(a=>{o||a.canHandle(t)&&(a.handle(e,t,r,n),o=!0)}),o},FS_createPreloadedFile=(e,t,r,n,o,a,s,i,l,c)=>{var u=t?PATH_FS.resolve(PATH.join2(e,t)):e,d=getUniqueRunDependency(`cp ${u}`);function m(r){function m(r){c&&c(),i||FS_createDataFile(e,t,r,n,o,l),a&&a(),removeRunDependency(d)}FS_handledByPreloadPlugin(r,u,m,()=>{s&&s(),removeRunDependency(d)})||m(r)}addRunDependency(d),"string"==typeof r?asyncLoad(r,e=>m(e),s):m(r)},FS_modeStringToFlags=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(void 0===t)throw new Error(`Unknown file open mode: ${e}`);return t},FS_getMode=(e,t)=>{var r=0;return e&&(r|=365),t&&(r|=146),r},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(!(e=PATH_FS.resolve(e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new FS.ErrnoError(32);for(var r=e.split("/").filter(e=>!!e),n=FS.root,o="/",a=0;a40)throw new FS.ErrnoError(32)}}return{path:o,node:n}},getPath(e){for(var t;;){if(FS.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?`${r}/${t}`:r+t:r}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var r=0,n=0;n>>0)%FS.nameTable.length},hashAddNode(e){var t=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[t],FS.nameTable[t]=e},hashRemoveNode(e){var t=FS.hashName(e.parent.id,e.name);if(FS.nameTable[t]===e)FS.nameTable[t]=e.name_next;else for(var r=FS.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode(e,t){var r=FS.mayLookup(e);if(r)throw new FS.ErrnoError(r,e);for(var n=FS.hashName(e.id,t),o=FS.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===t)return o}return FS.lookup(e,t)},createNode(e,t,r,n){var o=new FS.FSNode(e,t,r,n);return FS.hashAddNode(o),o},destroyNode(e){FS.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagsToPermissionString(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>FS.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup(e){var t=FS.nodePermissions(e,"x");return t||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{FS.lookupNode(e,t);return 20}catch(e){}return FS.nodePermissions(e,"wx")},mayDelete(e,t,r){var n;try{n=FS.lookupNode(e,t)}catch(e){return e.errno}var o=FS.nodePermissions(e,"wx");if(o)return o;if(r){if(!FS.isDir(n.mode))return 54;if(FS.isRoot(n)||FS.getPath(n)===FS.cwd())return 10}else if(FS.isDir(n.mode))return 31;return 0},mayOpen:(e,t)=>e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&("r"!==FS.flagsToPermissionString(t)||512&t)?31:FS.nodePermissions(e,FS.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var t=FS.getStream(e);if(!t)throw new FS.ErrnoError(8);return t},getStream:e=>FS.streams[e],createStream:(e,t=-1)=>(FS.FSStream||(FS.FSStream=function(){this.shared={}},FS.FSStream.prototype={},Object.defineProperties(FS.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return 1!=(2097155&this.flags)}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new FS.FSStream,e),-1==t&&(t=FS.nextfd()),e.fd=t,FS.streams[t]=e,e),closeStream(e){FS.streams[e]=null},chrdev_stream_ops:{open(e){var t=FS.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice(e,t){FS.devices[e]={stream_ops:t}},getDevice:e=>FS.devices[e],getMounts(e){for(var t=[],r=[e];r.length;){var n=r.pop();t.push(n),r.push.apply(r,n.mounts)}return t},syncfs(e,t){"function"==typeof e&&(t=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var r=FS.getMounts(FS.root.mount),n=0;function o(e){return FS.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=r.length&&o(null)}r.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,r){var n,o="/"===r,a=!r;if(o&&FS.root)throw new FS.ErrnoError(10);if(!o&&!a){var s=FS.lookupPath(r,{follow_mount:!1});if(r=s.path,n=s.node,FS.isMountpoint(n))throw new FS.ErrnoError(10);if(!FS.isDir(n.mode))throw new FS.ErrnoError(54)}var i={type:e,opts:t,mountpoint:r,mounts:[]},l=e.mount(i);return l.mount=i,i.root=l,o?FS.root=l:n&&(n.mounted=i,n.mount&&n.mount.mounts.push(i)),l},unmount(e){var t=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(t.node))throw new FS.ErrnoError(28);var r=t.node,n=r.mounted,o=FS.getMounts(n);Object.keys(FS.nameTable).forEach(e=>{for(var t=FS.nameTable[e];t;){var r=t.name_next;o.includes(t.mount)&&FS.destroyNode(t),t=r}}),r.mounted=null;var a=r.mount.mounts.indexOf(n);r.mount.mounts.splice(a,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod(e,t,r){var n=FS.lookupPath(e,{parent:!0}).node,o=PATH.basename(e);if(!o||"."===o||".."===o)throw new FS.ErrnoError(28);var a=FS.mayCreate(n,o);if(a)throw new FS.ErrnoError(a);if(!n.node_ops.mknod)throw new FS.ErrnoError(63);return n.node_ops.mknod(n,o,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,FS.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,FS.mknod(e,t,0)),mkdirTree(e,t){for(var r=e.split("/"),n="",o=0;o(void 0===r&&(r=t,t=438),t|=8192,FS.mknod(e,t,r)),symlink(e,t){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var r=FS.lookupPath(t,{parent:!0}).node;if(!r)throw new FS.ErrnoError(44);var n=PATH.basename(t),o=FS.mayCreate(r,n);if(o)throw new FS.ErrnoError(o);if(!r.node_ops.symlink)throw new FS.ErrnoError(63);return r.node_ops.symlink(r,n,e)},rename(e,t){var r,n,o=PATH.dirname(e),a=PATH.dirname(t),s=PATH.basename(e),i=PATH.basename(t);if(r=FS.lookupPath(e,{parent:!0}).node,n=FS.lookupPath(t,{parent:!0}).node,!r||!n)throw new FS.ErrnoError(44);if(r.mount!==n.mount)throw new FS.ErrnoError(75);var l,c=FS.lookupNode(r,s),u=PATH_FS.relative(e,a);if("."!==u.charAt(0))throw new FS.ErrnoError(28);if("."!==(u=PATH_FS.relative(t,o)).charAt(0))throw new FS.ErrnoError(55);try{l=FS.lookupNode(n,i)}catch(e){}if(c!==l){var d=FS.isDir(c.mode),m=FS.mayDelete(r,s,d);if(m)throw new FS.ErrnoError(m);if(m=l?FS.mayDelete(n,i,d):FS.mayCreate(n,i))throw new FS.ErrnoError(m);if(!r.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(c)||l&&FS.isMountpoint(l))throw new FS.ErrnoError(10);if(n!==r&&(m=FS.nodePermissions(r,"w")))throw new FS.ErrnoError(m);FS.hashRemoveNode(c);try{r.node_ops.rename(c,n,i)}catch(e){throw e}finally{FS.hashAddNode(c)}}},rmdir(e){var t=FS.lookupPath(e,{parent:!0}).node,r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!0);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.rmdir(t,r),FS.destroyNode(n)},readdir(e){var t=FS.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new FS.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=FS.lookupPath(e,{parent:!0}).node;if(!t)throw new FS.ErrnoError(44);var r=PATH.basename(e),n=FS.lookupNode(t,r),o=FS.mayDelete(t,r,!1);if(o)throw new FS.ErrnoError(o);if(!t.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(n))throw new FS.ErrnoError(10);t.node_ops.unlink(t,r),FS.destroyNode(n)},readlink(e){var t=FS.lookupPath(e).node;if(!t)throw new FS.ErrnoError(44);if(!t.node_ops.readlink)throw new FS.ErrnoError(28);return PATH_FS.resolve(FS.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var r=FS.lookupPath(e,{follow:!t}).node;if(!r)throw new FS.ErrnoError(44);if(!r.node_ops.getattr)throw new FS.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>FS.stat(e,!0),chmod(e,t,r){var n;"string"==typeof e?n=FS.lookupPath(e,{follow:!r}).node:n=e;if(!n.node_ops.setattr)throw new FS.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&t|-4096&n.mode,timestamp:Date.now()})},lchmod(e,t){FS.chmod(e,t,!0)},fchmod(e,t){var r=FS.getStreamChecked(e);FS.chmod(r.node,t)},chown(e,t,r,n){var o;"string"==typeof e?o=FS.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new FS.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown(e,t,r){FS.chown(e,t,r,!0)},fchown(e,t,r){var n=FS.getStreamChecked(e);FS.chown(n.node,t,r)},truncate(e,t){if(t<0)throw new FS.ErrnoError(28);var r;"string"==typeof e?r=FS.lookupPath(e,{follow:!0}).node:r=e;if(!r.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(r.mode))throw new FS.ErrnoError(31);if(!FS.isFile(r.mode))throw new FS.ErrnoError(28);var n=FS.nodePermissions(r,"w");if(n)throw new FS.ErrnoError(n);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate(e,t){var r=FS.getStreamChecked(e);if(!(2097155&r.flags))throw new FS.ErrnoError(28);FS.truncate(r.node,t)},utime(e,t,r){var n=FS.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(t,r)})},open(e,t,r){if(""===e)throw new FS.ErrnoError(44);var n;if(r=void 0===r?438:r,r=64&(t="string"==typeof t?FS_modeStringToFlags(t):t)?4095&r|32768:0,"object"==typeof e)n=e;else{e=PATH.normalize(e);try{n=FS.lookupPath(e,{follow:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(n){if(128&t)throw new FS.ErrnoError(20)}else n=FS.mknod(e,r,0),o=!0;if(!n)throw new FS.ErrnoError(44);if(FS.isChrdev(n.mode)&&(t&=-513),65536&t&&!FS.isDir(n.mode))throw new FS.ErrnoError(54);if(!o){var a=FS.mayOpen(n,t);if(a)throw new FS.ErrnoError(a)}512&t&&!o&&FS.truncate(n,0),t&=-131713;var s=FS.createStream({node:n,path:FS.getPath(n),flags:t,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!Module.logReadFiles||1&t||(FS.readFiles||(FS.readFiles={}),e in FS.readFiles||(FS.readFiles[e]=1)),s},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{FS.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read(e,t,r,n,o){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(1==(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var s=e.stream_ops.read(e,t,r,n,o);return a||(e.position+=s),s},write(e,t,r,n,o,a){if(n<0||o<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&1024&e.flags&&FS.llseek(e,0,2);var s=void 0!==o;if(s){if(!e.seekable)throw new FS.ErrnoError(70)}else o=e.position;var i=e.stream_ops.write(e,t,r,n,o,a);return s||(e.position+=i),i},allocate(e,t,r){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(t<0||r<=0)throw new FS.ErrnoError(28);if(!(2097155&e.flags))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap(e,t,r,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new FS.ErrnoError(2);if(1==(2097155&e.flags))throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);return e.stream_ops.mmap(e,t,r,n,o)},msync:(e,t,r,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,t,r,n,o):0,munmap:e=>0,ioctl(e,t,r){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error(`Invalid encoding type "${t.encoding}"`);var r,n=FS.open(e,t.flags),o=FS.stat(e).size,a=new Uint8Array(o);return FS.read(n,a,0,o,0),"utf8"===t.encoding?r=UTF8ArrayToString(a,0):"binary"===t.encoding&&(r=a),FS.close(n),r},writeFile(e,t,r={}){r.flags=r.flags||577;var n=FS.open(e,r.flags,r.mode);if("string"==typeof t){var o=new Uint8Array(lengthBytesUTF8(t)+1),a=stringToUTF8Array(t,o,0,o.length);FS.write(n,o,0,a,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");FS.write(n,t,0,t.byteLength,void 0,r.canOwn)}FS.close(n)},cwd:()=>FS.currentPath,chdir(e){var t=FS.lookupPath(e,{follow:!0});if(null===t.node)throw new FS.ErrnoError(44);if(!FS.isDir(t.node.mode))throw new FS.ErrnoError(54);var r=FS.nodePermissions(t.node,"x");if(r)throw new FS.ErrnoError(r);FS.currentPath=t.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(e,t,r,n,o)=>n}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),t=0,r=()=>(0===t&&(t=randomFill(e).byteLength),e[--t]);FS.createDevice("/dev","random",r),FS.createDevice("/dev","urandom",r),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var t=FS.createNode(e,"fd",16895,73);return t.node_ops={lookup(e,t){var r=+t,n=FS.getStreamChecked(r),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},t}},{},"/proc/self/fd")},createStandardStreams(){Module.stdin?FS.createDevice("/dev","stdin",Module.stdin):FS.symlink("/dev/tty","/dev/stdin"),Module.stdout?FS.createDevice("/dev","stdout",null,Module.stdout):FS.symlink("/dev/tty","/dev/stdout"),Module.stderr?FS.createDevice("/dev","stderr",null,Module.stderr):FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},ensureErrnoError(){FS.ErrnoError||(FS.ErrnoError=function(e,t){this.name="ErrnoError",this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},FS.ErrnoError.prototype=new Error,FS.ErrnoError.prototype.constructor=FS.ErrnoError,[44].forEach(e=>{FS.genericErrors[e]=new FS.ErrnoError(e),FS.genericErrors[e].stack=""}))},staticInit(){FS.ensureErrnoError(),FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS:MEMFS}},init(e,t,r){FS.init.initialized=!0,FS.ensureErrnoError(),Module.stdin=e||Module.stdin,Module.stdout=t||Module.stdout,Module.stderr=r||Module.stderr,FS.createStandardStreams()},quit(){FS.init.initialized=!1;for(var e=0;ethis.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,n=Number(e.getResponseHeader("Content-length")),o=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,a=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,s=1048576;o||(s=n);var i=this;i.setDataGetter(e=>{var t=e*s,o=(e+1)*s-1;if(o=Math.min(o,n-1),void 0===i.chunks[e]&&(i.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",r,!1),n!==s&&o.setRequestHeader("Range","bytes="+e+"-"+t),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+r+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):intArrayFromString(o.responseText||"",!0)})(t,o)),void 0===i.chunks[e])throw new Error("doXHR failed!");return i.chunks[e]}),!a&&n||(s=n=1,n=this.getter(0).length,s=n,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=s,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new a;Object.defineProperties(s,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var i={isDevice:!1,contents:s}}else i={isDevice:!1,url:r};var l=FS.createFile(e,t,i,n,o);i.contents?l.contents=i.contents:i.url&&(l.contents=null,l.url=i.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var c={};function u(e,t,r,n,o){var a=e.node.contents;if(o>=a.length)return 0;var s=Math.min(a.length-o,n);if(a.slice)for(var i=0;i{var t=l.stream_ops[e];c[e]=function(){return FS.forceLoadFile(l),t.apply(null,arguments)}}),c.read=(e,t,r,n,o)=>(FS.forceLoadFile(l),u(e,t,r,n,o)),c.mmap=(e,t,r,n,o)=>{FS.forceLoadFile(l);var a=mmapAlloc(t);if(!a)throw new FS.ErrnoError(48);return u(e,HEAP8,a,t,r),{ptr:a,allocated:!0}},l.stream_ops=c,l}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,t,r){if(PATH.isAbs(t))return t;var n;-100===e?n=FS.cwd():n=SYSCALLS.getStreamFromFD(e).path;if(0==t.length){if(!r)throw new FS.ErrnoError(44);return n}return PATH.join2(n,t)},doStat(e,t,r){try{var n=e(t)}catch(e){if(e&&e.node&&PATH.normalize(t)!==PATH.normalize(FS.getPath(e.node)))return-54;throw e}HEAP32[r>>2]=n.dev,HEAP32[r+4>>2]=n.mode,HEAPU32[r+8>>2]=n.nlink,HEAP32[r+12>>2]=n.uid,HEAP32[r+16>>2]=n.gid,HEAP32[r+20>>2]=n.rdev,tempI64=[n.size>>>0,(tempDouble=n.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+24>>2]=tempI64[0],HEAP32[r+28>>2]=tempI64[1],HEAP32[r+32>>2]=4096,HEAP32[r+36>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),s=n.ctime.getTime();return tempI64=[Math.floor(o/1e3)>>>0,(tempDouble=Math.floor(o/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+40>>2]=tempI64[0],HEAP32[r+44>>2]=tempI64[1],HEAPU32[r+48>>2]=o%1e3*1e3,tempI64=[Math.floor(a/1e3)>>>0,(tempDouble=Math.floor(a/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+56>>2]=tempI64[0],HEAP32[r+60>>2]=tempI64[1],HEAPU32[r+64>>2]=a%1e3*1e3,tempI64=[Math.floor(s/1e3)>>>0,(tempDouble=Math.floor(s/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+72>>2]=tempI64[0],HEAP32[r+76>>2]=tempI64[1],HEAPU32[r+80>>2]=s%1e3*1e3,tempI64=[n.ino>>>0,(tempDouble=n.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[r+88>>2]=tempI64[0],HEAP32[r+92>>2]=tempI64[1],0},doMsync(e,t,r,n,o){if(!FS.isFile(t.node.mode))throw new FS.ErrnoError(43);if(2&n)return 0;var a=HEAPU8.slice(e,e+r);FS.msync(t,a,o,r,n)},varargs:void 0,get(){var e=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},getp:()=>SYSCALLS.get(),getStr:e=>UTF8ToString(e),getStreamFromFD:e=>FS.getStreamChecked(e)};function ___syscall__newselect(e,t,r,n,o){try{for(var a=0,s=t?HEAP32[t>>2]:0,i=t?HEAP32[t+4>>2]:0,l=r?HEAP32[r>>2]:0,c=r?HEAP32[r+4>>2]:0,u=n?HEAP32[n>>2]:0,d=n?HEAP32[n+4>>2]:0,m=0,_=0,f=0,p=0,g=0,S=0,h=(t?HEAP32[t>>2]:0)|(r?HEAP32[r>>2]:0)|(n?HEAP32[n>>2]:0),E=(t?HEAP32[t+4>>2]:0)|(r?HEAP32[r+4>>2]:0)|(n?HEAP32[n+4>>2]:0),v=function(e,t,r,n){return e<32?t&n:r&n},F=0;F>2]:0)+(t?HEAP32[o+8>>2]:0)/1e6);D=w.stream_ops.poll(w,b)}1&D&&v(F,s,i,y)&&(F<32?m|=y:_|=y,a++),4&D&&v(F,l,c,y)&&(F<32?f|=y:p|=y,a++),2&D&&v(F,u,d,y)&&(F<32?g|=y:S|=y,a++)}}return t&&(HEAP32[t>>2]=m,HEAP32[t+4>>2]=_),r&&(HEAP32[r>>2]=f,HEAP32[r+4>>2]=p),n&&(HEAP32[n>>2]=g,HEAP32[n+4>>2]=S),a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var SOCKFS={mount:e=>(Module.websocket=Module.websocket&&"object"==typeof Module.websocket?Module.websocket:{},Module.websocket._callbacks={},Module.websocket.on=function(e,t){return"function"==typeof t&&(this._callbacks[e]=t),this},Module.websocket.emit=function(e,t){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,t)},FS.createNode(null,"/",16895,0)),createSocket(e,t,r){if(1==(t&=-526337)&&r&&6!=r)throw new FS.ErrnoError(66);var n={family:e,type:t,protocol:r,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},o=SOCKFS.nextname(),a=FS.createNode(SOCKFS.root,o,49152,0);a.sock=n;var s=FS.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return n.stream=s,n},getSocket(e){var t=FS.getStream(e);return t&&FS.isSocket(t.node.mode)?t.node.sock:null},stream_ops:{poll(e){var t=e.node.sock;return t.sock_ops.poll(t)},ioctl(e,t,r){var n=e.node.sock;return n.sock_ops.ioctl(n,t,r)},read(e,t,r,n,o){var a=e.node.sock,s=a.sock_ops.recvmsg(a,n);return s?(t.set(s.buffer,r),s.buffer.length):0},write(e,t,r,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,t,r,n)},close(e){var t=e.node.sock;t.sock_ops.close(t)}},nextname:()=>(SOCKFS.nextname.current||(SOCKFS.nextname.current=0),"socket["+SOCKFS.nextname.current+++"]"),websocket_sock_ops:{createPeer(e,t,r){var n;if("object"==typeof t&&(n=t,t=null,r=null),n)if(n._socket)t=n._socket.remoteAddress,r=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");t=o[1],r=parseInt(o[2],10)}else try{var a=Module.websocket&&"object"==typeof Module.websocket,s="ws:#".replace("#","//");if(a&&"string"==typeof Module.websocket.url&&(s=Module.websocket.url),"ws://"===s||"wss://"===s){var i=t.split("/");s=s+i[0]+":"+r+"/"+i.slice(1).join("/")}var l="binary";a&&"string"==typeof Module.websocket.subprotocol&&(l=Module.websocket.subprotocol);var c=void 0;"null"!==l&&(c=l=l.replace(/^ +| +$/g,"").split(/ *, */)),a&&null===Module.websocket.subprotocol&&(l="null",c=void 0),(n=new WebSocket(s,c)).binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}var u={addr:t,port:r,socket:n,dgram_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,u),SOCKFS.websocket_sock_ops.handlePeerEvents(e,u),2===e.type&&void 0!==e.sport&&u.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),u},getPeer:(e,t,r)=>e.peers[t+":"+r],addPeer(e,t){e.peers[t.addr+":"+t.port]=t},removePeer(e,t){delete e.peers[t.addr+":"+t.port]},handlePeerEvents(e,t){var r=!0,n=function(){Module.websocket.emit("open",e.stream.fd);try{for(var r=t.dgram_send_queue.shift();r;)t.socket.send(r),r=t.dgram_send_queue.shift()}catch(e){t.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(assert(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=r;if(r=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var a=n[8]<<8|n[9];return SOCKFS.websocket_sock_ops.removePeer(e,t),t.port=a,void SOCKFS.websocket_sock_ops.addPeer(e,t)}e.recv_queue.push({addr:t.addr,port:t.port,data:n}),Module.websocket.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(t.socket.on("open",n),t.socket.on("message",function(e,t){t&&o(new Uint8Array(e).buffer)}),t.socket.on("close",function(){Module.websocket.emit("close",e.stream.fd)}),t.socket.on("error",function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(t.socket.onopen=n,t.socket.onclose=function(){Module.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){o(e.data)},t.socket.onerror=function(t){e.error=14,Module.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(1===e.type&&e.server)return e.pending.length?65:0;var t=0,r=1===e.type?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!r||r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=65),(!r||r&&r.socket.readyState===r.socket.OPEN)&&(t|=4),(r&&r.socket.readyState===r.socket.CLOSING||r&&r.socket.readyState===r.socket.CLOSED)&&(t|=16),t},ioctl(e,t,r){if(21531===t){var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),HEAP32[r>>2]=n,0}return 28},close(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var t=Object.keys(e.peers),r=0;r{var t=SOCKFS.getSocket(e);if(!t)throw new FS.ErrnoError(8);return t},setErrNo=e=>(HEAP32[___errno_location()>>2]=e,e),inetNtop4=e=>(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var t="",r=0,n=0,o=0,a=0,s=0,i=0,l=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,u="";for(i=0;i<5;i++)if(0!==l[i]){c=!1;break}if(c){if(u=inetNtop4(l[6]|l[7]<<16),-1===l[5])return t="::ffff:",t+=u;if(0===l[5])return t="::","0.0.0.0"===u&&(u=""),"0.0.0.1"===u&&(u="1"),t+=u}for(r=0;r<8;r++)0===l[r]&&(r-o>1&&(s=0),o=r,s++),s>n&&(a=r-(n=s)+1);for(r=0;r<8;r++)n>1&&0===l[r]&&r>=a&&r{var r,n=HEAP16[e>>1],o=_ntohs(HEAPU16[e+2>>1]);switch(n){case 2:if(16!==t)return{errno:28};r=HEAP32[e+4>>2],r=inetNtop4(r);break;case 10:if(28!==t)return{errno:28};r=[HEAP32[e+8>>2],HEAP32[e+12>>2],HEAP32[e+16>>2],HEAP32[e+20>>2]],r=inetNtop6(r);break;default:return{errno:5}}return{family:n,addr:r,port:o}},inetPton4=e=>{for(var t=e.split("."),r=0;r<4;r++){var n=Number(t[r]);if(isNaN(n))return null;t[r]=n}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var t,r,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jstoi_q(t[t.length-4])+256*jstoi_q(t[t.length-3]),t[t.length-3]=jstoi_q(t[t.length-2])+256*jstoi_q(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),n=0,o=0,r=0;rDNS.address_map.names[e]?DNS.address_map.names[e]:null},getSocketAddress=(e,t,r)=>{if(r&&0===e)return null;var n=readSockaddr(e,t);if(n.errno)throw new FS.ErrnoError(n.errno);return n.addr=DNS.lookup_addr(n.addr)||n.addr,n};function ___syscall_connect(e,t,r,n,o,a){try{var s=getSocketFromFD(e),i=getSocketAddress(t,r);return s.sock_ops.connect(s,i.addr,i.port),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_faccessat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),-8&r)return-28;var o=FS.lookupPath(t,{follow:!0}).node;if(!o)return-44;var a="";return 4&r&&(a+="r"),2&r&&(a+="w"),1&r&&(a+="x"),a&&FS.nodePermissions(o,a)?-2:0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fcntl64(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 0:if((o=SYSCALLS.get())<0)return-28;for(;FS.streams[o];)o++;return FS.createStream(n,o).fd;case 1:case 2:case 6:case 7:return 0;case 3:return n.flags;case 4:var o=SYSCALLS.get();return n.flags|=o,0;case 5:o=SYSCALLS.getp();return HEAP16[o+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return setErrNo(28),-1}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_fstat64(e,t){try{var r=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,r.path,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_ioctl(e,t,r){SYSCALLS.varargs=r;try{var n=SYSCALLS.getStreamFromFD(e);switch(t){case 21509:case 21510:case 21511:case 21512:case 21524:case 21515:return n.tty?0:-59;case 21505:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var o=n.tty.ops.ioctl_tcgets(n),a=SYSCALLS.getp();HEAP32[a>>2]=o.c_iflag||0,HEAP32[a+4>>2]=o.c_oflag||0,HEAP32[a+8>>2]=o.c_cflag||0,HEAP32[a+12>>2]=o.c_lflag||0;for(var s=0;s<32;s++)HEAP8[a+s+17|0]=o.c_cc[s]||0;return 0}return 0;case 21506:case 21507:case 21508:if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){a=SYSCALLS.getp();var i=HEAP32[a>>2],l=HEAP32[a+4>>2],c=HEAP32[a+8>>2],u=HEAP32[a+12>>2],d=[];for(s=0;s<32;s++)d.push(HEAP8[a+s+17|0]);return n.tty.ops.ioctl_tcsets(n.tty,t,{c_iflag:i,c_oflag:l,c_cflag:c,c_lflag:u,c_cc:d})}return 0;case 21519:if(!n.tty)return-59;a=SYSCALLS.getp();return HEAP32[a>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:a=SYSCALLS.getp();return FS.ioctl(n,t,a);case 21523:if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var m=n.tty.ops.ioctl_tiocgwinsz(n.tty);a=SYSCALLS.getp();HEAP16[a>>1]=m[0],HEAP16[a+2>>1]=m[1]}return 0;default:return-28}}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_mkdirat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),"/"===(t=PATH.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),FS.mkdir(t,r,0),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_newfstatat(e,t,r,n){try{t=SYSCALLS.getStr(t);var o=256&n,a=4096&n;return n&=-6401,t=SYSCALLS.calculateAt(e,t,a),SYSCALLS.doStat(o?FS.lstat:FS.stat,t,r)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_openat(e,t,r,n){SYSCALLS.varargs=n;try{t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t);var o=n?SYSCALLS.get():0;return FS.open(t,r,o).fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var stringToUTF8=(e,t,r)=>stringToUTF8Array(e,HEAPU8,t,r);function ___syscall_readlinkat(e,t,r,n){try{if(t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),n<=0)return-28;var o=FS.readlink(t),a=Math.min(n,lengthBytesUTF8(o)),s=HEAP8[r+a];return stringToUTF8(o,r,n+1),HEAP8[r+a]=s,a}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_rmdir(e){try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_socket(e,t,r){try{return SOCKFS.createSocket(e,t,r).stream.fd}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_stat64(e,t){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,t)}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}function ___syscall_unlinkat(e,t,r){try{return t=SYSCALLS.getStr(t),t=SYSCALLS.calculateAt(e,t),0===r?FS.unlink(t):512===r?FS.rmdir(t):abort("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return-e.errno}}var nowIsMonotonic=!0,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic,convertI32PairToI53Checked=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*t:NaN;function __gmtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getUTCSeconds(),HEAP32[r+4>>2]=o.getUTCMinutes(),HEAP32[r+8>>2]=o.getUTCHours(),HEAP32[r+12>>2]=o.getUTCDate(),HEAP32[r+16>>2]=o.getUTCMonth(),HEAP32[r+20>>2]=o.getUTCFullYear()-1900,HEAP32[r+24>>2]=o.getUTCDay();var a=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),s=(o.getTime()-a)/864e5|0;HEAP32[r+28>>2]=s}var isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>(isLeapYear(e.getFullYear())?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE)[e.getMonth()]+e.getDate()-1;function __localtime_js(e,t,r){var n=convertI32PairToI53Checked(e,t),o=new Date(1e3*n);HEAP32[r>>2]=o.getSeconds(),HEAP32[r+4>>2]=o.getMinutes(),HEAP32[r+8>>2]=o.getHours(),HEAP32[r+12>>2]=o.getDate(),HEAP32[r+16>>2]=o.getMonth(),HEAP32[r+20>>2]=o.getFullYear()-1900,HEAP32[r+24>>2]=o.getDay();var a=0|ydayFromDate(o);HEAP32[r+28>>2]=a,HEAP32[r+36>>2]=-60*o.getTimezoneOffset();var s=new Date(o.getFullYear(),0,1),i=new Date(o.getFullYear(),6,1).getTimezoneOffset(),l=s.getTimezoneOffset(),c=0|(i!=l&&o.getTimezoneOffset()==Math.min(l,i));HEAP32[r+32>>2]=c}var _emscripten_get_now,stringToNewUTF8=e=>{var t=lengthBytesUTF8(e)+1,r=_malloc(t);return r&&stringToUTF8(e,r,t),r},__tzset_js=(e,t,r)=>{var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),s=o.getTimezoneOffset(),i=a.getTimezoneOffset(),l=Math.max(s,i);function c(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}HEAPU32[e>>2]=60*l,HEAP32[t>>2]=Number(s!=i);var u=c(o),d=c(a),m=stringToNewUTF8(u),_=stringToNewUTF8(d);i>2]=m,HEAPU32[r+4>>2]=_):(HEAPU32[r>>2]=_,HEAPU32[r+4>>2]=m)},_abort=()=>{abort("")},_emscripten_date_now=()=>Date.now(),getHeapMax=()=>2147483648,_emscripten_get_heap_max=()=>getHeapMax();_emscripten_get_now=()=>performance.now();var reallyNegative=e=>e<0||0===e&&1/e==-1/0,convertI32PairToI53=(e,t)=>(e>>>0)+4294967296*t,convertU32PairToI53=(e,t)=>(e>>>0)+4294967296*(t>>>0),reSign=(e,t)=>{if(e<=0)return e;var r=t<=32?Math.abs(1<=r&&(t<=32||e>r)&&(e=-2*r+e),e},unSign=(e,t)=>e>=0?e:t<=32?2*Math.abs(1<{for(var t=e;HEAPU8[t];)++t;return t-e},formatString=(e,t)=>{var r=e,n=t;function o(e){var t;return n=function(e,t){return"double"!==t&&"i64"!==t||7&e&&(e+=4),e}(n,e),"double"===e?(t=HEAPF64[n>>3],n+=8):"i64"==e?(t=[HEAP32[n>>2],HEAP32[n+4>>2]],n+=8):(e="i32",t=HEAP32[n>>2],n+=4),t}for(var a,s,i,l=[];;){var c=r;if(0===(a=HEAP8[r|0]))break;if(s=HEAP8[r+1|0],37==a){var u=!1,d=!1,m=!1,_=!1,f=!1;e:for(;;){switch(s){case 43:u=!0;break;case 45:d=!0;break;case 35:m=!0;break;case 48:if(_)break e;_=!0;break;case 32:f=!0;break;default:break e}r++,s=HEAP8[r+1|0]}var p=0;if(42==s)p=o("i32"),r++,s=HEAP8[r+1|0];else for(;s>=48&&s<=57;)p=10*p+(s-48),r++,s=HEAP8[r+1|0];var g,S=!1,h=-1;if(46==s){if(h=0,S=!0,r++,42==(s=HEAP8[r+1|0]))h=o("i32"),r++;else for(;;){var E=HEAP8[r+1|0];if(E<48||E>57)break;h=10*h+(E-48),r++}s=HEAP8[r+1|0]}switch(h<0&&(h=6,S=!1),String.fromCharCode(s)){case"h":104==HEAP8[r+2|0]?(r++,g=1):g=2;break;case"l":108==HEAP8[r+2|0]?(r++,g=8):g=4;break;case"L":case"q":case"j":g=8;break;case"z":case"t":case"I":g=4;break;default:g=null}switch(g&&r++,s=HEAP8[r+1|0],String.fromCharCode(s)){case"d":case"i":case"u":case"o":case"x":case"X":case"p":var v=100==s||105==s;if(i=o("i"+8*(g=g||4)),8==g&&(i=117==s?convertU32PairToI53(i[0],i[1]):convertI32PairToI53(i[0],i[1])),g<=4){var F=Math.pow(256,g)-1;i=(v?reSign:unSign)(i&F,8*g)}var y=Math.abs(i),w="";if(100==s||105==s)k=reSign(i,8*g).toString(10);else if(117==s)k=unSign(i,8*g).toString(10),i=Math.abs(i);else if(111==s)k=(m?"0":"")+y.toString(8);else if(120==s||88==s){if(w=m&&0!=i?"0x":"",i<0){i=-i,k=(y-1).toString(16);for(var D=[],b=0;b=0&&(u?w="+"+w:f&&(w=" "+w)),"-"==k.charAt(0)&&(w="-"+w,k=k.substr(1));w.length+k.lengthR&&R>=-4?(s=(103==s?"f":"F").charCodeAt(0),h-=R+1):(s=(103==s?"e":"E").charCodeAt(0),h--),C=Math.min(h,20)}101==s||69==s?(k=i.toExponential(C),/[eE][-+]\d$/.test(k)&&(k=k.slice(0,-1)+"0"+k.slice(-1))):102!=s&&70!=s||(k=i.toFixed(C),0===i&&reallyNegative(i)&&(k="-"+k));var A=k.split("e");if(T&&!m)for(;A[0].length>1&&A[0].includes(".")&&("0"==A[0].slice(-1)||"."==A[0].slice(-1));)A[0]=A[0].slice(0,-1);else for(m&&-1==k.indexOf(".")&&(A[0]+=".");h>C++;)A[0]+="0";k=A[0]+(A.length>1?"e"+A[1]:""),69==s&&(k=k.toUpperCase()),i>=0&&(u?k="+"+k:f&&(k=" "+k))}else k=(i<0?"-":"")+"inf",_=!1;for(;k.length0;)l.push(32);d||l.push(o("i8"));break;case"n":var M=o("i32*");HEAP32[M>>2]=l.length;break;case"%":l.push(a);break;default:for(b=c;b{warnOnce.shown||(warnOnce.shown={}),warnOnce.shown[e]||(warnOnce.shown[e]=1,err(e))};function getCallstack(e){var t=jsStackTrace(),r=t.lastIndexOf("_emscripten_log"),n=t.lastIndexOf("_emscripten_get_callstack"),o=t.indexOf("\n",Math.max(r,n))+1;t=t.slice(o),8&e&&"undefined"==typeof emscripten_source_map&&(warnOnce('Source map information is not available, emscripten_log with EM_LOG_C_STACK will be ignored. Build with "--pre-js $EMSCRIPTEN/src/emscripten-source-map.min.js" linker flag to add source map loading to code.'),e^=8,e|=16);var a=t.split("\n");t="";var s=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)"),i=new RegExp("\\s*(.*?)@(.*):(.*)(:(.*))?"),l=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var c in a){var u=a[c],d="",m="",_=0,f=0,p=l.exec(u);if(p&&5==p.length)d=p[1],m=p[2],_=p[3],f=p[4];else{if((p=s.exec(u))||(p=i.exec(u)),!(p&&p.length>=4)){t+=u+"\n";continue}d=p[1],m=p[2],_=p[3],f=0|p[4]}var g=!1;if(8&e){var S=emscripten_source_map.originalPositionFor({line:_,column:f});(g=S&&S.source)&&(64&e&&(S.source=S.source.substring(S.source.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=` at ${d} (${S.source}:${S.line}:${S.column})\n`)}(16&e||!g)&&(64&e&&(m=m.substring(m.replace(/\\/g,"/").lastIndexOf("/")+1)),t+=(g?` = ${d}`:` at ${d}`)+` (${m}:${_}:${f})\n`)}return t=t.replace(/\s+$/,"")}var emscriptenLog=(e,t)=>{24&e&&(t=t.replace(/\s+$/,""),t+=(t.length>0?"\n":"")+getCallstack(e)),1&e?4&e||2&e?err(t):out(t):6&e?err(t):out(t)},_emscripten_log=(e,t,r)=>{var n=formatString(t,r),o=UTF8ArrayToString(n,0);emscriptenLog(e,o)},growMemory=e=>{var t=(e-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch(e){}},_emscripten_resize_heap=e=>{var t=HEAPU8.length;e>>>=0;var r=getHeapMax();if(e>r)return!1;for(var n=(e,t)=>e+(t-e%t)%t,o=1;o<=4;o*=2){var a=t*(1+.2/o);a=Math.min(a,e+100663296);var s=Math.min(r,n(Math.max(e,a),65536));if(growMemory(s))return!0}return!1},ENV={},getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(var t in ENV)void 0===ENV[t]?delete e[t]:e[t]=ENV[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToAscii=(e,t)=>{for(var r=0;r{var r=0;return getEnvStrings().forEach((n,o)=>{var a=t+r;HEAPU32[e+4*o>>2]=a,stringToAscii(n,a),r+=n.length+1}),0},_environ_sizes_get=(e,t)=>{var r=getEnvStrings();HEAPU32[e>>2]=r.length;var n=0;return r.forEach(e=>n+=e.length+1),HEAPU32[t>>2]=n,0};function _fd_close(e){try{var t=SYSCALLS.getStreamFromFD(e);return FS.close(t),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doReadv=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.read(e,HEAP8,s,i,n);if(l<0)return-1;if(o+=l,l>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}function _fd_seek(e,t,r,n,o){var a=convertI32PairToI53Checked(t,r);try{if(isNaN(a))return 61;var s=SYSCALLS.getStreamFromFD(e);return FS.llseek(s,a,n),tempI64=[s.position>>>0,(tempDouble=s.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[o>>2]=tempI64[0],HEAP32[o+4>>2]=tempI64[1],s.getdents&&0===a&&0===n&&(s.getdents=null),0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var doWritev=(e,t,r,n)=>{for(var o=0,a=0;a>2],i=HEAPU32[t+4>>2];t+=8;var l=FS.write(e,HEAP8,s,i,n);if(l<0)return-1;o+=l,void 0!==n&&(n+=l)}return o};function _fd_write(e,t,r,n){try{var o=SYSCALLS.getStreamFromFD(e),a=doWritev(o,t,r);return HEAPU32[n>>2]=a,0}catch(e){if(void 0===FS||"ErrnoError"!==e.name)throw e;return e.errno}}var wasmTable,functionsInTableMap,arraySum=(e,t)=>{for(var r=0,n=0;n<=t;r+=e[n++]);return r},MONTH_DAYS_LEAP=[31,29,31,30,31,30,31,31,30,31,30,31],MONTH_DAYS_REGULAR=[31,28,31,30,31,30,31,31,30,31,30,31],addDays=(e,t)=>{for(var r=new Date(e.getTime());t>0;){var n=isLeapYear(r.getFullYear()),o=r.getMonth(),a=(n?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR)[o];if(!(t>a-r.getDate()))return r.setDate(r.getDate()+t),r;t-=a-r.getDate()+1,r.setDate(1),o<11?r.setMonth(o+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r},writeArrayToMemory=(e,t)=>{HEAP8.set(e,t)},_strftime=(e,t,r,n)=>{var o=HEAPU32[n+40>>2],a={tm_sec:HEAP32[n>>2],tm_min:HEAP32[n+4>>2],tm_hour:HEAP32[n+8>>2],tm_mday:HEAP32[n+12>>2],tm_mon:HEAP32[n+16>>2],tm_year:HEAP32[n+20>>2],tm_wday:HEAP32[n+24>>2],tm_yday:HEAP32[n+28>>2],tm_isdst:HEAP32[n+32>>2],tm_gmtoff:HEAP32[n+36>>2],tm_zone:o?UTF8ToString(o):""},s=UTF8ToString(r),i={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var l in i)s=s.replace(new RegExp(l,"g"),i[l]);var c=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"];function d(e,t,r){for(var n="number"==typeof e?e.toString():e||"";n.length0?1:0}var n;return 0===(n=r(e.getFullYear()-t.getFullYear()))&&0===(n=r(e.getMonth()-t.getMonth()))&&(n=r(e.getDate()-t.getDate())),n}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function p(e){var t=addDays(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),n=new Date(t.getFullYear()+1,0,4),o=f(r),a=f(n);return _(o,t)<=0?_(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var g={"%a":e=>c[e.tm_wday].substring(0,3),"%A":e=>c[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>m((e.tm_year+1900)/100|0,2),"%d":e=>m(e.tm_mday,2),"%e":e=>d(e.tm_mday,2," "),"%g":e=>p(e).toString().substring(2),"%G":e=>p(e),"%H":e=>m(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),m(t,2)},"%j":e=>m(e.tm_mday+arraySum(isLeapYear(e.tm_year+1900)?MONTH_DAYS_LEAP:MONTH_DAYS_REGULAR,e.tm_mon-1),3),"%m":e=>m(e.tm_mon+1,2),"%M":e=>m(e.tm_min,2),"%n":()=>"\n","%p":e=>e.tm_hour>=0&&e.tm_hour<12?"AM":"PM","%S":e=>m(e.tm_sec,2),"%t":()=>"\t","%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return m(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&isLeapYear(e.tm_year)||(t=1)}}else{t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(4==n||5==n&&isLeapYear(e.tm_year%400-1))&&t++}return m(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return m(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>"%"};for(var l in s=s.replace(/%%/g,"\0\0"),g)s.includes(l)&&(s=s.replace(new RegExp(l,"g"),g[l](a)));var S=intArrayFromString(s=s.replace(/\0\0/g,"%"),!1);return S.length>t?0:(writeArrayToMemory(S,e),S.length-1)},_strftime_l=(e,t,r,n,o)=>_strftime(e,t,r,n),getWasmTableEntry=e=>wasmTable.get(e),uleb128Encode=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var t={i:"i32",j:"i64",f:"f32",d:"f64",p:"i32"},r={parameters:[],results:"v"==e[0]?[]:[t[e[0]]]},n=1;n{var r=e.slice(0,1),n=e.slice(1),o={i:127,p:127,j:126,f:125,d:124};t.push(96),uleb128Encode(n.length,t);for(var a=0;a{if("function"==typeof WebAssembly.Function)return new WebAssembly.Function(sigToWasmTypes(t),e);var r=[1];generateFuncType(t,r);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(r.length,n),n.push.apply(n,r),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var o=new WebAssembly.Module(new Uint8Array(n));return new WebAssembly.Instance(o,{e:{f:e}}).exports.f},updateTableMap=(e,t)=>{if(functionsInTableMap)for(var r=e;r(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1},setWasmTableEntry=(e,t)=>wasmTable.set(e,t),addFunction=(e,t)=>{var r=getFunctionAddress(e);if(r)return r;var n=getEmptyTableSlot();try{setWasmTableEntry(n,e)}catch(r){if(!(r instanceof TypeError))throw r;var o=convertJsFunctionToWasm(e,t);setWasmTableEntry(n,o)}return functionsInTableMap.set(e,n),n},stringToUTF8OnStack=e=>{var t=lengthBytesUTF8(e)+1,r=stackAlloc(t);return stringToUTF8(e,r,t),r},FSNode=function(e,t,r,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=FS.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=n},readMode=365,writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(e){e?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(e){e?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}}),FS.FSNode=FSNode,FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit();var calledRun,wasmImports={CreateDirectoryFetcher:_CreateDirectoryFetcher,DDN_ConvertElement:_DDN_ConvertElement,DDN_CreateDDNResult:_DDN_CreateDDNResult,DDN_CreateDDNResultItem:_DDN_CreateDDNResultItem,DDN_CreateIntermediateResultUnits:_DDN_CreateIntermediateResultUnits,DDN_CreateParameters:_DDN_CreateParameters,DDN_CreateTargetRoiDefConditionFilter:_DDN_CreateTargetRoiDefConditionFilter,DDN_CreateTaskAlgEntity:_DDN_CreateTaskAlgEntity,DDN_HasSection:_DDN_HasSection,DDN_ReadTaskSetting:_DDN_ReadTaskSetting,DLR_ConvertElement:_DLR_ConvertElement,DLR_CreateBufferedCharacterItemSet:_DLR_CreateBufferedCharacterItemSet,DLR_CreateIntermediateResultUnits:_DLR_CreateIntermediateResultUnits,DLR_CreateParameters:_DLR_CreateParameters,DLR_CreateRecognizedTextLinesResult:_DLR_CreateRecognizedTextLinesResult,DLR_CreateTargetRoiDefConditionFilter:_DLR_CreateTargetRoiDefConditionFilter,DLR_CreateTaskAlgEntity:_DLR_CreateTaskAlgEntity,DLR_CreateTextLineResultItem:_DLR_CreateTextLineResultItem,DLR_ReadTaskSetting:_DLR_ReadTaskSetting,DMImage_GetDIB:_DMImage_GetDIB,DMImage_GetOrientation:_DMImage_GetOrientation,DeleteDirectoryFetcher:_DeleteDirectoryFetcher,_ZN19LabelRecognizerWasm10getVersionEv:__ZN19LabelRecognizerWasm10getVersionEv,_ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv:__ZN19LabelRecognizerWasm12DlrWasmClass15clearVerifyListEv,_ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv:__ZN19LabelRecognizerWasm12DlrWasmClass22getDuplicateForgetTimeEv,_ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi:__ZN19LabelRecognizerWasm12DlrWasmClass22setDuplicateForgetTimeEi,_ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb:__ZN19LabelRecognizerWasm12DlrWasmClass25enableResultDeduplicationEb,_ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb:__ZN19LabelRecognizerWasm12DlrWasmClass27getJvFromTextLineResultItemEPKN9dynamsoft3dlr19CTextLineResultItemEPKcb,_ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb:__ZN19LabelRecognizerWasm12DlrWasmClass29enableResultCrossVerificationEb,_ZN19LabelRecognizerWasm12DlrWasmClassC1Ev:__ZN19LabelRecognizerWasm12DlrWasmClassC1Ev,_ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE:__ZN19LabelRecognizerWasm24getJvFromCharacterResultEPKN9dynamsoft3dlr16CCharacterResultE,_ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE:__ZN19LabelRecognizerWasm26getJvBufferedCharacterItemEPKN9dynamsoft3dlr22CBufferedCharacterItemE,_ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE:__ZN19LabelRecognizerWasm29getJvLocalizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results25CLocalizedTextLineElementE,_ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE:__ZN19LabelRecognizerWasm30getJvRecognizedTextLineElementEPKN9dynamsoft3dlr20intermediate_results26CRecognizedTextLineElementE,_ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE:__ZN19LabelRecognizerWasm32getJvFromTextLineResultItem_JustEPKN9dynamsoft3dlr19CTextLineResultItemE,_ZN22DocumentNormalizerWasm10getVersionEv:__ZN22DocumentNormalizerWasm10getVersionEv,_ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv:__ZN22DocumentNormalizerWasm12DdnWasmClass15clearVerifyListEv,_ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi:__ZN22DocumentNormalizerWasm12DdnWasmClass22getDuplicateForgetTimeEi,_ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii:__ZN22DocumentNormalizerWasm12DdnWasmClass22setDuplicateForgetTimeEii,_ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass25enableResultDeduplicationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib:__ZN22DocumentNormalizerWasm12DdnWasmClass29enableResultCrossVerificationEib,_ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass31getJvFromDetectedQuadResultItemEPKN9dynamsoft3ddn23CDetectedQuadResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromDeskewedImageResultItemEPKN9dynamsoft3ddn24CDeskewedImageResultItemEPKcb,_ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE:__ZN22DocumentNormalizerWasm12DdnWasmClass32getJvFromEnhancedImageResultItemEPKN9dynamsoft3ddn24CEnhancedImageResultItemE,_ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev:__ZN22DocumentNormalizerWasm12DdnWasmClassC1Ev,_ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE:__ZN22DocumentNormalizerWasm36getJvFromDetectedQuadResultItem_JustEPKN9dynamsoft3ddn23CDetectedQuadResultItemE,_ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE:__ZN22DocumentNormalizerWasm37getJvFromDeskewedImageResultItem_JustEPKN9dynamsoft3ddn24CDeskewedImageResultItemE,_ZN9dynamsoft7utility14CUtilityModule10GetVersionEv:__ZN9dynamsoft7utility14CUtilityModule10GetVersionEv,__assert_fail:___assert_fail,__cxa_begin_catch:___cxa_begin_catch,__cxa_end_catch:___cxa_end_catch,__cxa_find_matching_catch_2:___cxa_find_matching_catch_2,__cxa_find_matching_catch_3:___cxa_find_matching_catch_3,__cxa_rethrow:___cxa_rethrow,__cxa_rethrow_primary_exception:___cxa_rethrow_primary_exception,__cxa_throw:___cxa_throw,__cxa_uncaught_exceptions:___cxa_uncaught_exceptions,__resumeException:___resumeException,__syscall__newselect:___syscall__newselect,__syscall_connect:___syscall_connect,__syscall_faccessat:___syscall_faccessat,__syscall_fcntl64:___syscall_fcntl64,__syscall_fstat64:___syscall_fstat64,__syscall_ioctl:___syscall_ioctl,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_readlinkat:___syscall_readlinkat,__syscall_rmdir:___syscall_rmdir,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_unlinkat:___syscall_unlinkat,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_tzset_js:__tzset_js,abort:_abort,emscripten_date_now:_emscripten_date_now,emscripten_get_heap_max:_emscripten_get_heap_max,emscripten_get_now:_emscripten_get_now,emscripten_log:_emscripten_log,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,invoke_diii:invoke_diii,invoke_fiii:invoke_fiii,invoke_i:invoke_i,invoke_ii:invoke_ii,invoke_iii:invoke_iii,invoke_iiii:invoke_iiii,invoke_iiiii:invoke_iiiii,invoke_iiiiid:invoke_iiiiid,invoke_iiiiii:invoke_iiiiii,invoke_iiiiiii:invoke_iiiiiii,invoke_iiiiiiii:invoke_iiiiiiii,invoke_iiiiiiiiiiii:invoke_iiiiiiiiiiii,invoke_iiiiij:invoke_iiiiij,invoke_j:invoke_j,invoke_ji:invoke_ji,invoke_jii:invoke_jii,invoke_jiiii:invoke_jiiii,invoke_v:invoke_v,invoke_vi:invoke_vi,invoke_vii:invoke_vii,invoke_viid:invoke_viid,invoke_viii:invoke_viii,invoke_viiii:invoke_viiii,invoke_viiiiiii:invoke_viiiiiii,invoke_viiiiiiiiii:invoke_viiiiiiiiii,invoke_viiiiiiiiiiiiiii:invoke_viiiiiiiiiiiiiii,strftime:_strftime,strftime_l:_strftime_l},wasmExports=createWasm();function invoke_iiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ii(e,t){var r=stackSave();try{return getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(e,t,r){var n=stackSave();try{return getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(e,t,r){var n=stackSave();try{getWasmTableEntry(e)(t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(e,t){var r=stackSave();try{getWasmTableEntry(e)(t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(e){var t=stackSave();try{getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(e,t,r,n,o,a,s){var i=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(e,t,r,n,o){var a=stackSave();try{getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiid(e,t,r,n,o,a){var s=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a)}catch(e){if(stackRestore(s),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(e,t,r,n,o){var a=stackSave();try{return getWasmTableEntry(e)(t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function invoke_fiii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_diii(e,t,r,n){var o=stackSave();try{return getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(e){var t=stackSave();try{return getWasmTableEntry(e)()}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiii(e,t,r,n,o,a,s,i){var l=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i)}catch(e){if(stackRestore(l),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,d){var m=stackSave();try{return getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,d)}catch(e){if(stackRestore(m),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u){var d=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u)}catch(e){if(stackRestore(d),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiii(e,t,r,n,o,a,s,i,l,c,u,d,m,_,f,p){var g=stackSave();try{getWasmTableEntry(e)(t,r,n,o,a,s,i,l,c,u,d,m,_,f,p)}catch(e){if(stackRestore(g),e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(e,t,r,n){var o=stackSave();try{getWasmTableEntry(e)(t,r,n)}catch(e){if(stackRestore(o),e!==e+0)throw e;_setThrew(1,0)}}function invoke_j(e){var t=stackSave();try{return dynCall_j(e)}catch(e){if(stackRestore(t),e!==e+0)throw e;_setThrew(1,0)}}function invoke_ji(e,t){var r=stackSave();try{return dynCall_ji(e,t)}catch(e){if(stackRestore(r),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jii(e,t,r){var n=stackSave();try{return dynCall_jii(e,t,r)}catch(e){if(stackRestore(n),e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiij(e,t,r,n,o,a,s){var i=stackSave();try{return dynCall_iiiiij(e,t,r,n,o,a,s)}catch(e){if(stackRestore(i),e!==e+0)throw e;_setThrew(1,0)}}function invoke_jiiii(e,t,r,n,o){var a=stackSave();try{return dynCall_jiiii(e,t,r,n,o)}catch(e){if(stackRestore(a),e!==e+0)throw e;_setThrew(1,0)}}function run(){function e(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT||(initRuntime(),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)]()[UTF8ToString(r)]()),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r)=>stringToUTF8OnStack((new(self[UTF8ToString(e)]))[UTF8ToString(t)](UTF8ToString(r))),"iiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>{self[UTF8ToString(e)](null,UTF8ToString(t).trim(),UTF8ToString(r),n)},"viiii")),wasmExports.emscripten_bind_funcs(addFunction((e,t,r,n)=>stringToUTF8OnStack(self[UTF8ToString(e)][UTF8ToString(t)][UTF8ToString(r)](UTF8ToString(n))?"":self[UTF8ToString(e)][UTF8ToString(t)]),"iiiii")),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun()))}runDependencies>0||(preRun(),runDependencies>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()))}if(Module.addFunction=addFunction,Module.stringToUTF8OnStack=stringToUTF8OnStack,dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)},Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();run(); \ No newline at end of file diff --git a/dist/dynamsoft-barcode-reader-bundle.wasm b/dist/dynamsoft-barcode-reader-bundle.wasm index 4c0448d..4f46f18 100644 Binary files a/dist/dynamsoft-barcode-reader-bundle.wasm and b/dist/dynamsoft-barcode-reader-bundle.wasm differ diff --git a/dist/models/Code128Decoder.data b/dist/models/Code128Decoder.data new file mode 100644 index 0000000..c13ad6c Binary files /dev/null and b/dist/models/Code128Decoder.data differ diff --git a/dist/models/DataMatrixQRCodeLocalization.data b/dist/models/DataMatrixQRCodeLocalization.data new file mode 100644 index 0000000..c5d7676 Binary files /dev/null and b/dist/models/DataMatrixQRCodeLocalization.data differ diff --git a/dist/models/EAN13Decoder.data b/dist/models/EAN13Decoder.data new file mode 100644 index 0000000..c804ab7 Binary files /dev/null and b/dist/models/EAN13Decoder.data differ diff --git a/dist/models/OneDDeblur.data b/dist/models/OneDDeblur.data index 6975164..20c02fe 100644 Binary files a/dist/models/OneDDeblur.data and b/dist/models/OneDDeblur.data differ diff --git a/dist/models/OneDLocalization.data b/dist/models/OneDLocalization.data new file mode 100644 index 0000000..1df2f7e Binary files /dev/null and b/dist/models/OneDLocalization.data differ diff --git a/dist/templates/DBR-PresetTemplates.json b/dist/templates/DBR-PresetTemplates.json index d6dafb4..172297c 100644 --- a/dist/templates/DBR-PresetTemplates.json +++ b/dist/templates/DBR-PresetTemplates.json @@ -1,4 +1,7 @@ { + "GlobalParameter": { + "IntraOpNumThreads": 2 + }, "BarcodeFormatSpecificationOptions": [ { "BarcodeFormatIds": [ @@ -72,16 +75,8 @@ "bfs2" ], "Name": "task-read-barcodes", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-barcodes", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-barcodes", "Section": "ST_BARCODE_LOCALIZATION", @@ -92,13 +87,10 @@ "Mode": "LM_CONNECTED_BLOCKS" }, { - "Mode": "LM_LINES" + "Mode": "LM_SCAN_DIRECTLY" } ], "Stage": "SST_LOCALIZE_CANDIDATE_BARCODES" - }, - { - "Stage": "SST_LOCALIZE_BARCODES" } ] }, @@ -106,15 +98,6 @@ "ImageParameterName": "ip-read-barcodes", "Section": "ST_BARCODE_DECODING", "StageArray": [ - { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { - "Stage": "SST_SCALE_BARCODE_IMAGE" - }, { "DeblurModes": [ { @@ -122,6 +105,20 @@ }, { "Mode": "DM_THRESHOLD_BINARIZATION" + }, + { + "Mode": "DM_NEURAL_NETWORK", + "ModelNameArray": [ + "Code128Decoder", + "EAN13Decoder" + ] + }, + { + "Mode": "DM_DEEP_ANALYSIS", + "Methods": [ + "OneDGeneral", + "TwoDGeneral" + ] } ], "Stage": "SST_DECODE_BARCODES" @@ -136,16 +133,8 @@ "bfs2-speed-first" ], "Name": "task-read-barcodes-speed-first", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-barcodes-speed-first", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-barcodes-speed-first", "Section": "ST_BARCODE_LOCALIZATION", @@ -153,17 +142,13 @@ { "LocalizationModes": [ { - "Mode": "LM_SCAN_DIRECTLY", - "ScanDirection": 2 + "Mode": "LM_CONNECTED_BLOCKS" }, { - "Mode": "LM_CONNECTED_BLOCKS" + "Mode": "LM_SCAN_DIRECTLY" } ], "Stage": "SST_LOCALIZE_CANDIDATE_BARCODES" - }, - { - "Stage": "SST_LOCALIZE_BARCODES" } ] }, @@ -171,15 +156,6 @@ "ImageParameterName": "ip-read-barcodes-speed-first", "Section": "ST_BARCODE_DECODING", "StageArray": [ - { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { - "Stage": "SST_SCALE_BARCODE_IMAGE" - }, { "DeblurModes": [ { @@ -189,7 +165,18 @@ "Mode": "DM_THRESHOLD_BINARIZATION" }, { - "Mode": "DM_DEEP_ANALYSIS" + "Mode": "DM_NEURAL_NETWORK", + "ModelNameArray": [ + "Code128Decoder", + "EAN13Decoder" + ] + }, + { + "Mode": "DM_DEEP_ANALYSIS", + "Methods": [ + "OneDGeneral", + "TwoDGeneral" + ] } ], "Stage": "SST_DECODE_BARCODES" @@ -205,16 +192,8 @@ ], "ExpectedBarcodesCount": 999, "Name": "task-read-barcodes-read-rate", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-barcodes-read-rate", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-barcodes-read-rate", "Section": "ST_BARCODE_LOCALIZATION", @@ -225,16 +204,10 @@ "Mode": "LM_CONNECTED_BLOCKS" }, { - "Mode": "LM_LINES" - }, - { - "Mode": "LM_STATISTICS" + "Mode": "LM_NEURAL_NETWORK" } ], "Stage": "SST_LOCALIZE_CANDIDATE_BARCODES" - }, - { - "Stage": "SST_LOCALIZE_BARCODES" } ] }, @@ -242,15 +215,6 @@ "ImageParameterName": "ip-read-barcodes-read-rate", "Section": "ST_BARCODE_DECODING", "StageArray": [ - { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { - "Stage": "SST_SCALE_BARCODE_IMAGE" - }, { "DeblurModes": [ { @@ -263,7 +227,10 @@ "Mode": "DM_DIRECT_BINARIZATION" }, { - "Mode": "DM_SMOOTHING" + "Mode": "DM_NEURAL_NETWORK" + }, + { + "Mode": "DM_DEEP_ANALYSIS" } ], "Stage": "SST_DECODE_BARCODES" @@ -279,16 +246,8 @@ ], "ExpectedBarcodesCount": 1, "Name": "task-read-single-barcode", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-single-barcode", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-single-barcode", "Section": "ST_BARCODE_LOCALIZATION", @@ -296,11 +255,10 @@ { "LocalizationModes": [ { - "Mode": "LM_SCAN_DIRECTLY", - "ScanDirection": 2 + "Mode": "LM_CONNECTED_BLOCKS" }, { - "Mode": "LM_CONNECTED_BLOCKS" + "Mode": "LM_SCAN_DIRECTLY" } ], "Stage": "SST_LOCALIZE_CANDIDATE_BARCODES" @@ -314,15 +272,6 @@ "ImageParameterName": "ip-read-single-barcode", "Section": "ST_BARCODE_DECODING", "StageArray": [ - { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { - "Stage": "SST_SCALE_BARCODE_IMAGE" - }, { "DeblurModes": [ { @@ -332,7 +281,18 @@ "Mode": "DM_THRESHOLD_BINARIZATION" }, { - "Mode": "DM_DEEP_ANALYSIS" + "Mode": "DM_NEURAL_NETWORK", + "ModelNameArray": [ + "Code128Decoder", + "EAN13Decoder" + ] + }, + { + "Mode": "DM_DEEP_ANALYSIS", + "Methods": [ + "OneDGeneral", + "TwoDGeneral" + ] } ], "Stage": "SST_DECODE_BARCODES" @@ -348,16 +308,8 @@ ], "ExpectedBarcodesCount": 999, "Name": "task-read-barcodes-balance", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-barcodes-balance", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-barcodes-balance", "Section": "ST_BARCODE_LOCALIZATION", @@ -382,15 +334,6 @@ "ImageParameterName": "ip-read-barcodes-balance", "Section": "ST_BARCODE_DECODING", "StageArray": [ - { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { - "Stage": "SST_SCALE_BARCODE_IMAGE" - }, { "DeblurModes": [ { @@ -415,16 +358,8 @@ "bfs2-dense" ], "Name": "task-read-barcodes-dense", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-barcodes-dense", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-barcodes-dense", "Section": "ST_BARCODE_LOCALIZATION", @@ -435,7 +370,7 @@ "Mode": "LM_CONNECTED_BLOCKS" }, { - "Mode": "LM_LINES" + "Mode": "LM_SCAN_DIRECTLY" } ], "Stage": "SST_LOCALIZE_CANDIDATE_BARCODES" @@ -449,15 +384,6 @@ "ImageParameterName": "ip-read-barcodes-dense", "Section": "ST_BARCODE_DECODING", "StageArray": [ - { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { - "Stage": "SST_SCALE_BARCODE_IMAGE" - }, { "DeblurModes": [ { @@ -467,13 +393,18 @@ "Mode": "DM_THRESHOLD_BINARIZATION" }, { - "Mode": "DM_DIRECT_BINARIZATION" + "Mode": "DM_NEURAL_NETWORK", + "ModelNameArray": [ + "Code128Decoder", + "EAN13Decoder" + ] }, { - "Mode": "DM_SMOOTHING" - }, - { - "Mode": "DM_GRAY_EQUALIZATION" + "Mode": "DM_DEEP_ANALYSIS", + "Methods": [ + "OneDGeneral", + "TwoDGeneral" + ] } ], "Stage": "SST_DECODE_BARCODES" @@ -488,16 +419,8 @@ "bfs2-distant" ], "Name": "task-read-barcodes-distant", + "MaxThreadsInOneTask": 1, "SectionArray": [ - { - "ImageParameterName": "ip-read-barcodes-distant", - "Section": "ST_REGION_PREDETECTION", - "StageArray": [ - { - "Stage": "SST_PREDETECT_REGIONS" - } - ] - }, { "ImageParameterName": "ip-read-barcodes-distant", "Section": "ST_BARCODE_LOCALIZATION", @@ -523,12 +446,13 @@ "Section": "ST_BARCODE_DECODING", "StageArray": [ { - "Stage": "SST_RESIST_DEFORMATION" - }, - { - "Stage": "SST_COMPLEMENT_BARCODE" - }, - { + "BarcodeScaleModes": [ + { + "Mode": "BSM_LINEAR_INTERPOLATION", + "ModuleSizeThreshold": 4, + "TargetModuleSize": 6 + } + ], "Stage": "SST_SCALE_BARCODE_IMAGE" }, { @@ -540,7 +464,18 @@ "Mode": "DM_THRESHOLD_BINARIZATION" }, { - "Mode": "DM_DIRECT_BINARIZATION" + "Mode": "DM_NEURAL_NETWORK", + "ModelNameArray": [ + "Code128Decoder", + "EAN13Decoder" + ] + }, + { + "Mode": "DM_DEEP_ANALYSIS", + "Methods": [ + "OneDGeneral", + "TwoDGeneral" + ] } ], "Stage": "SST_DECODE_BARCODES" @@ -561,7 +496,8 @@ "ImageROIProcessingNameArray": [ "roi-read-barcodes-speed-first" ], - "Name": "ReadBarcodes_SpeedFirst" + "Name": "ReadBarcodes_SpeedFirst", + "Timeout": 500 }, { "ImageROIProcessingNameArray": [ @@ -574,7 +510,8 @@ "ImageROIProcessingNameArray": [ "roi-read-single-barcode" ], - "Name": "ReadSingleBarcode" + "Name": "ReadSingleBarcode", + "Timeout": 500 }, { "ImageROIProcessingNameArray": [ @@ -587,13 +524,15 @@ "ImageROIProcessingNameArray": [ "roi-read-barcodes-dense" ], - "Name": "ReadDenseBarcodes" + "Name": "ReadDenseBarcodes", + "Timeout": 100000 }, { "ImageROIProcessingNameArray": [ "roi-read-barcodes-distant" ], - "Name": "ReadDistantBarcodes" + "Name": "ReadDistantBarcodes", + "Timeout": 100000 } ], "ImageParameterOptions": [ @@ -615,14 +554,6 @@ "Stage": "SST_ENHANCE_GRAYSCALE" }, { - "BinarizationModes": [ - { - "BlockSizeX": 71, - "BlockSizeY": 71, - "EnableFillBinaryVacancy": 0, - "Mode": "BM_LOCAL_BLOCK" - } - ], "Stage": "SST_BINARIZE_IMAGE" }, { @@ -916,6 +847,10 @@ "Stage": "SST_INPUT_COLOR_IMAGE" }, { + "ImageScaleSetting": { + "EdgeLengthThreshold": 10000, + "ScaleType": "ST_SCALE_DOWN" + }, "Stage": "SST_SCALE_IMAGE" }, { diff --git a/dist/ui/barcode-scanner.ui.xml b/dist/ui/barcode-scanner.ui.xml index 9aea2f2..375ba12 100644 --- a/dist/ui/barcode-scanner.ui.xml +++ b/dist/ui/barcode-scanner.ui.xml @@ -23,6 +23,7 @@ +
+
diff --git a/package.json b/package.json index 8dcc816..6269f5c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-barcode-reader-bundle", - "version": "11.0.6000", + "version": "11.2.2000", "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.", "main": "dist/dbr.bundle.js", "module": "dist/dbr.bundle.esm.js", @@ -75,13 +75,13 @@ "tag": "latest" }, "devDependencies": { - "@dynamsoft/dynamsoft-barcode-reader": "11.0.60-dev-20250812165905", - "@dynamsoft/dynamsoft-camera-enhancer": "4.2.3-dev-20250812165927", - "@dynamsoft/dynamsoft-capture-vision-router": "3.0.60-dev-20250812165839", - "@dynamsoft/dynamsoft-code-parser": "3.0.60-dev-20250812165958", - "@dynamsoft/dynamsoft-license": "4.0.60-dev-20250812170103", - "@dynamsoft/dynamsoft-utility": "2.0.60-dev-20250812170132", - "@dynamsoft/rd2-scripts": "^0.1.49", + "@dynamsoft/dynamsoft-barcode-reader": "11.2.20-dev-20251029130556", + "@dynamsoft/dynamsoft-camera-enhancer": "4.3.3-dev-20251029130621", + "@dynamsoft/dynamsoft-capture-vision-router": "3.2.20-dev-20251030140710", + "@dynamsoft/dynamsoft-code-parser": "3.2.20-dev-20251029130614", + "@dynamsoft/dynamsoft-license": "4.2.20-dev-20251029130543", + "@dynamsoft/dynamsoft-utility": "2.2.20-dev-20251029130550", + "@dynamsoft/rd2-scripts": "0.1.50", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-replace": "^5.0.5", "@rollup/plugin-terser": "^0.4.4", @@ -89,7 +89,7 @@ "@scannerproxy/curscript-path": "^2.0.6", "@scannerproxy/dlsjs": "3.0.39", "@types/node": "^22.15.3", - "dynamsoft-core": "npm:@dynamsoft/dynamsoft-core@4.0.60-dev-20250812165815", + "dynamsoft-core": "npm:@dynamsoft/dynamsoft-core@4.2.20-dev-20251029130528", "mutable-promise": "^1.1.15", "rollup": "^3.29.3", "rollup-plugin-dts": "^6.1.0", diff --git a/samples.url b/samples.url index 5dc7fc7..2112642 100644 --- a/samples.url +++ b/samples.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v11.0.60 \ No newline at end of file +URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v11.2.20 \ No newline at end of file