diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 6e006423a..9afb72a4d 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -5,7 +5,8 @@
"Bash(mkdir:*)",
"Bash(./gradlew:*)",
"Bash(grep:*)",
- "Bash(cat:*)"
+ "Bash(cat:*)",
+ "Bash(find:*)"
],
"deny": []
}
diff --git a/CLAUDE.md b/CLAUDE.md
index 05bfb5254..8bdd7c235 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,23 +25,54 @@ Set `DOCKER_ENABLE_SECURITY=true` environment variable to enable security featur
- **Proxy Configuration**: Vite proxies `/api/*` calls to backend (localhost:8080)
- **Build Process**: DO NOT run build scripts manually - builds are handled by CI/CD pipelines
- **Package Installation**: DO NOT run npm install commands - package management handled separately
+- **Deployment Options**:
+ - **Desktop App**: `npm run tauri-build` (native desktop application)
+ - **Web Server**: `npm run build` then serve dist/ folder
+ - **Development**: `npm run tauri-dev` for desktop dev mode
-#### Tailwind CSS Setup (if not already installed)
-```bash
-cd frontend
-npm install -D tailwindcss postcss autoprefixer
-npx tailwindcss init -p
-```
+#### Multi-Tool Workflow Architecture
+Frontend designed for **stateful document processing**:
+- Users upload PDFs once, then chain tools (split → merge → compress → view)
+- File state and processing results persist across tool switches
+- No file reloading between tools - performance critical for large PDFs (up to 100GB+)
+
+#### FileContext - Central State Management
+**Location**: `src/contexts/FileContext.tsx`
+- **Active files**: Currently loaded PDFs and their variants
+- **Tool navigation**: Current mode (viewer/pageEditor/fileEditor/toolName)
+- **Memory management**: PDF document cleanup, blob URL lifecycle, Web Worker management
+- **IndexedDB persistence**: File storage with thumbnail caching
+- **Preview system**: Tools can preview results (e.g., Split → Viewer → back to Split) without context pollution
+
+**Critical**: All file operations go through FileContext. Don't bypass with direct file handling.
+
+#### Processing Services
+- **enhancedPDFProcessingService**: Background PDF parsing and manipulation
+- **thumbnailGenerationService**: Web Worker-based with main-thread fallback
+- **fileStorage**: IndexedDB with LRU cache management
+
+#### Memory Management Strategy
+**Why manual cleanup exists**: Large PDFs (up to 100GB+) through multiple tools accumulate:
+- PDF.js documents that need explicit .destroy() calls
+- Blob URLs from tool outputs that need revocation
+- Web Workers that need termination
+Without cleanup: browser crashes with memory leaks.
+
+#### Tool Development
+- **Pattern**: Follow `src/tools/Split.tsx` as reference implementation
+- **File Access**: Tools receive `selectedFiles` prop (computed from activeFiles based on user selection)
+- **File Selection**: Users select files in FileEditor (tool mode) → stored as IDs → computed to File objects for tools
+- **Integration**: All files are part of FileContext ecosystem - automatic memory management and operation tracking
+- **Parameters**: Tool parameter handling patterns still being standardized
+- **Preview Integration**: Tools can implement preview functionality (see Split tool's thumbnail preview)
## Architecture Overview
### Project Structure
- **Backend**: Spring Boot application with Thymeleaf templating
-- **Frontend**: React-based SPA in `/frontend` directory (replacing legacy Thymeleaf templates)
- - **Current Status**: Active development to replace Thymeleaf UI with modern React SPA
+- **Frontend**: React-based SPA in `/frontend` directory (Thymeleaf templates fully replaced)
- **File Storage**: IndexedDB for client-side file persistence and thumbnails
- **Internationalization**: JSON-based translations (converted from backend .properties)
- - **URL Parameters**: Deep linking support for tool states and configurations
- **PDF Processing**: PDFBox for core PDF operations, LibreOffice for conversions, PDF.js for client-side rendering
- **Security**: Spring Security with optional authentication (controlled by `DOCKER_ENABLE_SECURITY`)
- **Configuration**: YAML-based configuration with environment variable overrides
@@ -59,9 +90,8 @@ npx tailwindcss init -p
- **Pipeline System**: Automated PDF processing workflows via `PipelineController`
- **Security Layer**: Authentication, authorization, and user management (when enabled)
-### Template System (Legacy + Modern)
-- **Legacy Thymeleaf Templates**: Located in `src/main/resources/templates/` (being phased out)
-- **Modern React Components**: Located in `frontend/src/components/` and `frontend/src/tools/`
+### Component Architecture
+- **React Components**: Located in `frontend/src/components/` and `frontend/src/tools/`
- **Static Assets**: CSS, JS, and resources in `src/main/resources/static/` (legacy) + `frontend/public/` (modern)
- **Internationalization**:
- Backend: `messages_*.properties` files
@@ -91,13 +121,14 @@ npx tailwindcss init -p
- Frontend: Update JSON files in `frontend/public/locales/` or use conversion script
5. **Documentation**: API docs auto-generated and available at `/swagger-ui/index.html`
-## Frontend Migration Notes
+## Frontend Architecture Status
-- **Current Branch**: `feature/react-overhaul` - Active React SPA development
-- **Migration Status**: Core tools (Split, Merge, Compress) converted to React with URL parameter support
-- **File Management**: Implemented IndexedDB storage with thumbnail generation using PDF.js
-- **Tools Architecture**: Each tool receives `params` and `updateParams` for URL state synchronization
-- **Remaining Work**: Convert remaining Thymeleaf templates to React components
+- **Core Status**: React SPA architecture complete with multi-tool workflow support
+- **State Management**: FileContext handles all file operations and tool navigation
+- **File Processing**: Production-ready with memory management for large PDF workflows (up to 100GB+)
+- **Tool Integration**: Standardized tool interface - see `src/tools/Split.tsx` as reference
+- **Preview System**: Tool results can be previewed without polluting file context (Split tool example)
+- **Performance**: Web Worker thumbnails, IndexedDB persistence, background processing
## Important Notes
@@ -108,6 +139,11 @@ npx tailwindcss init -p
- **Backend**: Designed to be stateless - files are processed in memory/temp locations only
- **Frontend**: Uses IndexedDB for client-side file storage and caching (with thumbnails)
- **Security**: When `DOCKER_ENABLE_SECURITY=false`, security-related classes are excluded from compilation
+- **FileContext**: All file operations MUST go through FileContext - never bypass with direct File handling
+- **Memory Management**: Manual cleanup required for PDF.js documents and blob URLs - don't remove cleanup code
+- **Tool Development**: New tools should follow Split tool pattern (`src/tools/Split.tsx`)
+- **Performance Target**: Must handle PDFs up to 100GB+ without browser crashes
+- **Preview System**: Tools can preview results without polluting main file context (see Split tool implementation)
## Communication Style
- Be direct and to the point
diff --git a/common/src/main/java/stirling/software/common/service/TaskManager.java b/common/src/main/java/stirling/software/common/service/TaskManager.java
index 219ae4ac4..902b2bfd1 100644
--- a/common/src/main/java/stirling/software/common/service/TaskManager.java
+++ b/common/src/main/java/stirling/software/common/service/TaskManager.java
@@ -1,6 +1,5 @@
package stirling.software.common.service;
-import io.github.pixee.security.ZipSecurity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -21,6 +20,8 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
+import io.github.pixee.security.ZipSecurity;
+
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
@@ -361,7 +362,8 @@ public class TaskManager {
MultipartFile zipFile = fileStorage.retrieveFile(zipFileId);
try (ZipInputStream zipIn =
- ZipSecurity.createHardenedInputStream(new ByteArrayInputStream(zipFile.getBytes()))) {
+ ZipSecurity.createHardenedInputStream(
+ new ByteArrayInputStream(zipFile.getBytes()))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
if (!entry.isDirectory()) {
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 0e33392bc..6c19c7632 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -25,6 +25,7 @@
"i18next": "^25.2.1",
"i18next-browser-languagedetector": "^8.1.0",
"i18next-http-backend": "^3.0.2",
+ "jszip": "^3.10.1",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^3.11.174",
"react": "^19.1.0",
@@ -2689,6 +2690,11 @@
"node": ">=18"
}
},
+ "node_modules/core-util-is": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
+ },
"node_modules/cosmiconfig": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz",
@@ -3450,6 +3456,11 @@
"cross-fetch": "4.0.0"
}
},
+ "node_modules/immediate": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="
+ },
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@@ -3491,8 +3502,7 @@
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "license": "ISC",
- "optional": true
+ "license": "ISC"
},
"node_modules/is-arrayish": {
"version": "0.2.1",
@@ -3571,6 +3581,11 @@
"node": ">=0.12.0"
}
},
+ "node_modules/isarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
+ },
"node_modules/jiti": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.4.2.tgz",
@@ -3630,6 +3645,52 @@
"graceful-fs": "^4.1.6"
}
},
+ "node_modules/jszip": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
+ "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
+ "dependencies": {
+ "lie": "~3.3.0",
+ "pako": "~1.0.2",
+ "readable-stream": "~2.3.6",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/jszip/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "node_modules/jszip/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
+ },
+ "node_modules/jszip/node_modules/string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "dependencies": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
+ "node_modules/lie": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
+ "dependencies": {
+ "immediate": "~3.0.5"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.30.1",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.1.tgz",
@@ -4729,6 +4790,11 @@
"node": ">= 0.8"
}
},
+ "node_modules/process-nextick-args": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
+ },
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
@@ -5237,6 +5303,11 @@
"integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
"license": "MIT"
},
+ "node_modules/setimmediate": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="
+ },
"node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
@@ -5697,7 +5768,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
- "devOptional": true,
"license": "MIT"
},
"node_modules/vite": {
diff --git a/frontend/package.json b/frontend/package.json
index fa7a0b5d2..38dfbf56e 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -21,6 +21,7 @@
"i18next": "^25.2.1",
"i18next-browser-languagedetector": "^8.1.0",
"i18next-http-backend": "^3.0.2",
+ "jszip": "^3.10.1",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^3.11.174",
"react": "^19.1.0",
diff --git a/frontend/public/pdf.js b/frontend/public/pdf.js
new file mode 100644
index 000000000..c31b6ab62
--- /dev/null
+++ b/frontend/public/pdf.js
@@ -0,0 +1,22 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * JavaScript code in this page
+ *
+ * Copyright 2023 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * JavaScript code in this page
+ */
+!function webpackUniversalModuleDefinition(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=t.pdfjsLib=e():"function"==typeof define&&define.amd?define("pdfjs-dist/build/pdf",[],(()=>t.pdfjsLib=e())):"object"==typeof exports?exports["pdfjs-dist/build/pdf"]=t.pdfjsLib=e():t["pdfjs-dist/build/pdf"]=t.pdfjsLib=e()}(globalThis,(()=>(()=>{"use strict";var __webpack_modules__=[,(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});e.VerbosityLevel=e.Util=e.UnknownErrorException=e.UnexpectedResponseException=e.TextRenderingMode=e.RenderingIntentFlag=e.PromiseCapability=e.PermissionFlag=e.PasswordResponses=e.PasswordException=e.PageActionEventType=e.OPS=e.MissingPDFException=e.MAX_IMAGE_SIZE_TO_CACHE=e.LINE_FACTOR=e.LINE_DESCENT_FACTOR=e.InvalidPDFException=e.ImageKind=e.IDENTITY_MATRIX=e.FormatError=e.FeatureTest=e.FONT_IDENTITY_MATRIX=e.DocumentActionEventType=e.CMapCompressionType=e.BaseException=e.BASELINE_FACTOR=e.AnnotationType=e.AnnotationReplyType=e.AnnotationPrefix=e.AnnotationMode=e.AnnotationFlag=e.AnnotationFieldFlag=e.AnnotationEditorType=e.AnnotationEditorPrefix=e.AnnotationEditorParamsType=e.AnnotationBorderStyleType=e.AnnotationActionEventType=e.AbortException=void 0;e.assert=function assert(t,e){t||unreachable(e)};e.bytesToString=bytesToString;e.createValidAbsoluteUrl=function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=stringToUTF8String(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null};e.getModificationDate=function getModificationDate(t=new Date){return[t.getUTCFullYear().toString(),(t.getUTCMonth()+1).toString().padStart(2,"0"),t.getUTCDate().toString().padStart(2,"0"),t.getUTCHours().toString().padStart(2,"0"),t.getUTCMinutes().toString().padStart(2,"0"),t.getUTCSeconds().toString().padStart(2,"0")].join("")};e.getUuid=function getUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<32;e++)t[e]=Math.floor(255*Math.random());return bytesToString(t)};e.getVerbosityLevel=function getVerbosityLevel(){return n};e.info=function info(t){n>=s.INFOS&&console.log(`Info: ${t}`)};e.isArrayBuffer=function isArrayBuffer(t){return"object"==typeof t&&void 0!==t?.byteLength};e.isArrayEqual=function isArrayEqual(t,e){if(t.length!==e.length)return!1;for(let i=0,s=t.length;ie?e.normalize("NFKC"):h.get(i)))};e.objectFromMap=function objectFromMap(t){const e=Object.create(null);for(const[i,s]of t)e[i]=s;return e};e.objectSize=function objectSize(t){return Object.keys(t).length};e.setVerbosityLevel=function setVerbosityLevel(t){Number.isInteger(t)&&(n=t)};e.shadow=shadow;e.string32=function string32(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)};e.stringToBytes=stringToBytes;e.stringToPDFString=function stringToPDFString(t){if(t[0]>="ï"){let e;"þ"===t[0]&&"ÿ"===t[1]?e="utf-16be":"ÿ"===t[0]&&"þ"===t[1]?e="utf-16le":"ï"===t[0]&&"»"===t[1]&&"¿"===t[2]&&(e="utf-8");if(e)try{const i=new TextDecoder(e,{fatal:!0}),s=stringToBytes(t);return i.decode(s)}catch(t){warn(`stringToPDFString: "${t}".`)}}const e=[];for(let i=0,s=t.length;i=s.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const a=function BaseExceptionClosure(){function BaseException(t,e){this.constructor===BaseException&&unreachable("Cannot initialize BaseException.");this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();e.BaseException=a;e.PasswordException=class PasswordException extends a{constructor(t,e){super(t,"PasswordException");this.code=e}};e.UnknownErrorException=class UnknownErrorException extends a{constructor(t,e){super(t,"UnknownErrorException");this.details=e}};e.InvalidPDFException=class InvalidPDFException extends a{constructor(t){super(t,"InvalidPDFException")}};e.MissingPDFException=class MissingPDFException extends a{constructor(t){super(t,"MissingPDFException")}};e.UnexpectedResponseException=class UnexpectedResponseException extends a{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}};e.FormatError=class FormatError extends a{constructor(t){super(t,"FormatError")}};e.AbortException=class AbortException extends a{constructor(t){super(t,"AbortException")}};function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));e.Util=class Util{static makeHexColor(t,e,i){return`#${r[t]}${r[e]}${r[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[1];e[1]=i}e[0]*=t[0];e[1]*=t[0];if(t[3]<0){i=e[2];e[2]=e[3];e[3]=i}e[2]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[2];e[2]=i;i=e[1];e[1]=e[3];e[3]=i;if(t[1]<0){i=e[2];e[2]=e[3];e[3]=i}e[2]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[1];e[1]=i}e[0]*=t[2];e[1]*=t[2]}e[0]+=t[4];e[1]+=t[4];e[2]+=t[5];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),a=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],a[0]),Math.min(i[1],s[1],n[1],a[1]),Math.max(i[0],s[0],n[0],a[0]),Math.max(i[1],s[1],n[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(i+a)/2,o=Math.sqrt((i+a)**2-4*(i*a-n*s))/2,l=r+o||1,h=r-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>a?null:[i,n,s,a]}static bezierBoundingBox(t,e,i,s,n,a,r,o){const l=[],h=[[],[]];let c,d,u,p,g,m,f,b;for(let h=0;h<2;++h){if(0===h){d=6*t-12*i+6*n;c=-3*t+9*i-9*n+3*r;u=3*i-3*t}else{d=6*e-12*s+6*a;c=-3*e+9*s-9*a+3*o;u=3*s-3*e}if(Math.abs(c)<1e-12){if(Math.abs(d)<1e-12)continue;p=-u/d;0
{this.resolve=e=>{this.#t=!0;t(e)};this.reject=t=>{this.#t=!0;e(t)}}))}get settled(){return this.#t}};let l=null,h=null;e.AnnotationPrefix="pdfjs_internal_id_"},(__unused_webpack_module,exports,__w_pdfjs_require__)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.RenderTask=exports.PDFWorkerUtil=exports.PDFWorker=exports.PDFPageProxy=exports.PDFDocumentProxy=exports.PDFDocumentLoadingTask=exports.PDFDataRangeTransport=exports.LoopbackPort=exports.DefaultStandardFontDataFactory=exports.DefaultFilterFactory=exports.DefaultCanvasFactory=exports.DefaultCMapReaderFactory=void 0;Object.defineProperty(exports,"SVGGraphics",{enumerable:!0,get:function(){return _displaySvg.SVGGraphics}});exports.build=void 0;exports.getDocument=getDocument;exports.version=void 0;var _util=__w_pdfjs_require__(1),_annotation_storage=__w_pdfjs_require__(3),_display_utils=__w_pdfjs_require__(6),_font_loader=__w_pdfjs_require__(9),_displayNode_utils=__w_pdfjs_require__(10),_canvas=__w_pdfjs_require__(11),_worker_options=__w_pdfjs_require__(14),_message_handler=__w_pdfjs_require__(15),_metadata=__w_pdfjs_require__(16),_optional_content_config=__w_pdfjs_require__(17),_transport_stream=__w_pdfjs_require__(18),_displayFetch_stream=__w_pdfjs_require__(19),_displayNetwork=__w_pdfjs_require__(22),_displayNode_stream=__w_pdfjs_require__(23),_displaySvg=__w_pdfjs_require__(24),_xfa_text=__w_pdfjs_require__(25);const DEFAULT_RANGE_CHUNK_SIZE=65536,RENDERING_CANCELLED_TIMEOUT=100,DELAYED_CLEANUP_TIMEOUT=5e3,DefaultCanvasFactory=_util.isNodeJS?_displayNode_utils.NodeCanvasFactory:_display_utils.DOMCanvasFactory;exports.DefaultCanvasFactory=DefaultCanvasFactory;const DefaultCMapReaderFactory=_util.isNodeJS?_displayNode_utils.NodeCMapReaderFactory:_display_utils.DOMCMapReaderFactory;exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory;const DefaultFilterFactory=_util.isNodeJS?_displayNode_utils.NodeFilterFactory:_display_utils.DOMFilterFactory;exports.DefaultFilterFactory=DefaultFilterFactory;const DefaultStandardFontDataFactory=_util.isNodeJS?_displayNode_utils.NodeStandardFontDataFactory:_display_utils.DOMStandardFontDataFactory;exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory;function getDocument(t){"string"==typeof t||t instanceof URL?t={url:t}:(0,_util.isArrayBuffer)(t)&&(t={data:t});if("object"!=typeof t)throw new Error("Invalid parameter in getDocument, need parameter object.");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");const e=new PDFDocumentLoadingTask,{docId:i}=e,s=t.url?getUrlProp(t.url):null,n=t.data?getDataProp(t.data):null,a=t.httpHeaders||null,r=!0===t.withCredentials,o=t.password??null,l=t.range instanceof PDFDataRangeTransport?t.range:null,h=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:DEFAULT_RANGE_CHUNK_SIZE;let c=t.worker instanceof PDFWorker?t.worker:null;const d=t.verbosity,u="string"!=typeof t.docBaseUrl||(0,_display_utils.isDataScheme)(t.docBaseUrl)?null:t.docBaseUrl,p="string"==typeof t.cMapUrl?t.cMapUrl:null,g=!1!==t.cMapPacked,m=t.CMapReaderFactory||DefaultCMapReaderFactory,f="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,b=t.StandardFontDataFactory||DefaultStandardFontDataFactory,A=!0!==t.stopAtErrors,_=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,v=!1!==t.isEvalSupported,y="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!_util.isNodeJS,S=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,E="boolean"==typeof t.disableFontFace?t.disableFontFace:_util.isNodeJS,x=!0===t.fontExtraProperties,w=!0===t.enableXfa,C=t.ownerDocument||globalThis.document,T=!0===t.disableRange,P=!0===t.disableStream,M=!0===t.disableAutoFetch,k=!0===t.pdfBug,F=l?l.length:t.length??NaN,R="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!_util.isNodeJS&&!E,D="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:m===_display_utils.DOMCMapReaderFactory&&b===_display_utils.DOMStandardFontDataFactory&&p&&f&&(0,_display_utils.isValidFetchUrl)(p,document.baseURI)&&(0,_display_utils.isValidFetchUrl)(f,document.baseURI),I=t.canvasFactory||new DefaultCanvasFactory({ownerDocument:C}),L=t.filterFactory||new DefaultFilterFactory({docId:i,ownerDocument:C});(0,_util.setVerbosityLevel)(d);const O={canvasFactory:I,filterFactory:L};if(!D){O.cMapReaderFactory=new m({baseUrl:p,isCompressed:g});O.standardFontDataFactory=new b({baseUrl:f})}if(!c){const t={verbosity:d,port:_worker_options.GlobalWorkerOptions.workerPort};c=t.port?PDFWorker.fromPort(t):new PDFWorker(t);e._worker=c}const N={docId:i,apiVersion:"3.11.174",data:n,password:o,disableAutoFetch:M,rangeChunkSize:h,length:F,docBaseUrl:u,enableXfa:w,evaluatorOptions:{maxImageSize:_,disableFontFace:E,ignoreErrors:A,isEvalSupported:v,isOffscreenCanvasSupported:y,canvasMaxAreaInBytes:S,fontExtraProperties:x,useSystemFonts:R,cMapUrl:D?p:null,standardFontDataUrl:D?f:null}},B={ignoreErrors:A,isEvalSupported:v,disableFontFace:E,fontExtraProperties:x,enableXfa:w,ownerDocument:C,disableAutoFetch:M,pdfBug:k,styleElement:null};c.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");const t=_fetchDocument(c,N),o=new Promise((function(t){let e;if(l)e=new _transport_stream.PDFDataTransportStream({length:F,initialData:l.initialData,progressiveDone:l.progressiveDone,contentDispositionFilename:l.contentDispositionFilename,disableRange:T,disableStream:P},l);else if(!n){e=(t=>_util.isNodeJS?new _displayNode_stream.PDFNodeStream(t):(0,_display_utils.isValidFetchUrl)(t.url)?new _displayFetch_stream.PDFFetchStream(t):new _displayNetwork.PDFNetworkStream(t))({url:s,length:F,httpHeaders:a,withCredentials:r,rangeChunkSize:h,disableRange:T,disableStream:P})}t(e)}));return Promise.all([t,o]).then((function([t,s]){if(e.destroyed)throw new Error("Loading aborted");const n=new _message_handler.MessageHandler(i,t,c.port),a=new WorkerTransport(n,e,s,B,O);e._transport=a;n.send("Ready",null)}))})).catch(e._capability.reject);return e}async function _fetchDocument(t,e){if(t.destroyed)throw new Error("Worker was destroyed");const i=await t.messageHandler.sendWithPromise("GetDocRequest",e,e.data?[e.data.buffer]:null);if(t.destroyed)throw new Error("Worker was destroyed");return i}function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(_util.isNodeJS&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function getDataProp(t){if(_util.isNodeJS&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return(0,_util.stringToBytes)(t);if("object"==typeof t&&!isNaN(t?.length)||(0,_util.isArrayBuffer)(t))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}class PDFDocumentLoadingTask{static#e=0;constructor(){this._capability=new _util.PromiseCapability;this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#e++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;if(this._worker){this._worker.destroy();this._worker=null}}}exports.PDFDocumentLoadingTask=PDFDocumentLoadingTask;class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=new _util.PromiseCapability}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){(0,_util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}exports.PDFDataRangeTransport=PDFDataRangeTransport;class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e;Object.defineProperty(this,"getJavaScript",{value:()=>{(0,_display_utils.deprecated)("`PDFDocumentProxy.getJavaScript`, please use `PDFDocumentProxy.getJSActions` instead.");return this.getJSActions().then((t=>{if(!t)return t;const e=[];for(const i in t)e.push(...t[i]);return e}))}})}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,_util.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig(){return this._transport.getOptionalContentConfig()}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}exports.PDFDocumentProxy=PDFDocumentProxy;class PDFPageProxy{#i=null;#s=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new _display_utils.StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new _display_utils.PageViewport({viewBox:this.view,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const e=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e.renderingIntent)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,_util.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=_util.AnnotationMode.ENABLE,transform:n=null,background:a=null,optionalContentConfigPromise:r=null,annotationCanvasMap:o=null,pageColors:l=null,printAnnotationStorage:h=null}){this._stats?.time("Overall");const c=this._transport.getRenderingIntent(i,s,h);this.#s=!1;this.#n();r||(r=this._transport.getOptionalContentConfig());let d=this._intentStates.get(c.cacheKey);if(!d){d=Object.create(null);this._intentStates.set(c.cacheKey,d)}if(d.streamReaderCancelTimeout){clearTimeout(d.streamReaderCancelTimeout);d.streamReaderCancelTimeout=null}const u=!!(c.renderingIntent&_util.RenderingIntentFlag.PRINT);if(!d.displayReadyCapability){d.displayReadyCapability=new _util.PromiseCapability;d.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(c)}const complete=t=>{d.renderTasks.delete(p);(this._maybeCleanupAfterRender||u)&&(this.#s=!0);this.#a(!u);if(t){p.capability.reject(t);this._abortOperatorList({intentState:d,reason:t instanceof Error?t:new Error(t)})}else p.capability.resolve();this._stats?.timeEnd("Rendering");this._stats?.timeEnd("Overall")},p=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:d.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!u,pdfBug:this._pdfBug,pageColors:l});(d.renderTasks||=new Set).add(p);const g=p.task;Promise.all([d.displayReadyCapability.promise,r]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");p.initializeGraphics({transparency:t,optionalContentConfig:e});p.operatorListChanged()}})).catch(complete);return g}getOperatorList({intent:t="display",annotationMode:e=_util.AnnotationMode.ENABLE,printAnnotationStorage:i=null}={}){const s=this._transport.getRenderingIntent(t,e,i,!0);let n,a=this._intentStates.get(s.cacheKey);if(!a){a=Object.create(null);this._intentStates.set(s.cacheKey,a)}if(!a.opListReadCapability){n=Object.create(null);n.operatorListChanged=function operatorListChanged(){if(a.operatorList.lastChunk){a.opListReadCapability.resolve(a.operatorList);a.renderTasks.delete(n)}};a.opListReadCapability=new _util.PromiseCapability;(a.renderTasks||=new Set).add(n);a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(s)}return a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>_xfa_text.XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null)};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#s=!1;this.#n();return Promise.all(t)}cleanup(t=!1){this.#s=!0;const e=this.#a(!1);t&&e&&(this._stats&&=new _display_utils.StatTimer);return e}#a(t=!1){this.#n();if(!this.#s||this.destroyed)return!1;if(t){this.#i=setTimeout((()=>{this.#i=null;this.#a(!1)}),DELAYED_CLEANUP_TIMEOUT);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#s=!1;return!0}#n(){if(this.#i){clearTimeout(this.#i);this.#i=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i 0){const t=1e3*o.measureText(a).width/r*l;if(y{a.read().then((({value:t,done:e})=>{if(e)r.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,r);pump()}}),(t=>{r.streamReader=null;if(!this._transport.destroyed){if(r.operatorList){r.operatorList.lastChunk=!0;for(const t of r.renderTasks)t.operatorListChanged();this.#a(!0)}if(r.displayReadyCapability)r.displayReadyCapability.reject(t);else{if(!r.opListReadCapability)throw t;r.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof _display_utils.RenderingCancelledException){let i=RENDERING_CANCELLED_TIMEOUT;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new _util.AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}exports.PDFPageProxy=PDFPageProxy;class LoopbackPort{#r=new Set;#o=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#o.then((()=>{for(const t of this.#r)t.call(this,i)}))}addEventListener(t,e){this.#r.add(e)}removeEventListener(t,e){this.#r.delete(e)}terminate(){this.#r.clear()}}exports.LoopbackPort=LoopbackPort;const PDFWorkerUtil={isWorkerDisabled:!1,fallbackWorkerSrc:null,fakeWorkerId:0};exports.PDFWorkerUtil=PDFWorkerUtil;if(_util.isNodeJS&&"function"==typeof require){PDFWorkerUtil.isWorkerDisabled=!0;PDFWorkerUtil.fallbackWorkerSrc="./pdf.worker.js"}else if("object"==typeof document){const t=document?.currentScript?.src;t&&(PDFWorkerUtil.fallbackWorkerSrc=t.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2"))}PDFWorkerUtil.isSameOrigin=function(t,e){let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};PDFWorkerUtil.createCDNWrapper=function(t){const e=`importScripts("${t}");`;return URL.createObjectURL(new Blob([e]))};class PDFWorker{static#l;constructor({name:t=null,port:e=null,verbosity:i=(0,_util.getVerbosityLevel)()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=new _util.PromiseCapability;this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#l?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#l||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new _message_handler.MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!PDFWorkerUtil.isWorkerDisabled&&!PDFWorker._mainThreadWorkerMessageHandler){let{workerSrc:t}=PDFWorker;try{PDFWorkerUtil.isSameOrigin(window.location.href,t)||(t=PDFWorkerUtil.createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t),i=new _message_handler.MessageHandler("main","worker",e),terminateEarly=()=>{e.removeEventListener("error",onWorkerError);i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},onWorkerError=()=>{this._webWorker||terminateEarly()};e.addEventListener("error",onWorkerError);i.on("test",(t=>{e.removeEventListener("error",onWorkerError);if(this.destroyed)terminateEarly();else if(t){this._messageHandler=i;this._port=e;this._webWorker=e;this._readyCapability.resolve();i.send("configure",{verbosity:this.verbosity})}else{this._setupFakeWorker();i.destroy();e.terminate()}}));i.on("ready",(t=>{e.removeEventListener("error",onWorkerError);if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{(0,_util.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorkerUtil.isWorkerDisabled){(0,_util.warn)("Setting up fake worker.");PDFWorkerUtil.isWorkerDisabled=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorkerUtil.fakeWorkerId++,s=new _message_handler.MessageHandler(i+"_worker",i,e);t.setup(s,e);const n=new _message_handler.MessageHandler(i,i+"_worker",e);this._messageHandler=n;this._readyCapability.resolve();n.send("configure",{verbosity:this.verbosity})})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;if(this._webWorker){this._webWorker.terminate();this._webWorker=null}PDFWorker.#l?.delete(this._port);this._port=null;if(this._messageHandler){this._messageHandler.destroy();this._messageHandler=null}}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#l?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(_worker_options.GlobalWorkerOptions.workerSrc)return _worker_options.GlobalWorkerOptions.workerSrc;if(null!==PDFWorkerUtil.fallbackWorkerSrc){_util.isNodeJS||(0,_display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');return PDFWorkerUtil.fallbackWorkerSrc}throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _mainThreadWorkerMessageHandler(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){const loader=async()=>{const mainWorkerMessageHandler=this._mainThreadWorkerMessageHandler;if(mainWorkerMessageHandler)return mainWorkerMessageHandler;if(_util.isNodeJS&&"function"==typeof require){const worker=eval("require")(this.workerSrc);return worker.WorkerMessageHandler}await(0,_display_utils.loadScript)(this.workerSrc);return window.pdfjsWorker.WorkerMessageHandler};return(0,_util.shadow)(this,"_setupFakeWorkerGlobal",loader())}}exports.PDFWorker=PDFWorker;class WorkerTransport{#h=new Map;#c=new Map;#d=new Map;#u=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new _font_loader.FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=new _util.PromiseCapability;this.setupMessageHandler()}#p(t,e=null){const i=this.#h.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#h.set(t,s);return s}get annotationStorage(){return(0,_util.shadow)(this,"annotationStorage",new _annotation_storage.AnnotationStorage)}getRenderingIntent(t,e=_util.AnnotationMode.ENABLE,i=null,s=!1){let n=_util.RenderingIntentFlag.DISPLAY,a=_annotation_storage.SerializableEmpty;switch(t){case"any":n=_util.RenderingIntentFlag.ANY;break;case"display":break;case"print":n=_util.RenderingIntentFlag.PRINT;break;default:(0,_util.warn)(`getRenderingIntent - invalid intent: ${t}`)}switch(e){case _util.AnnotationMode.DISABLE:n+=_util.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case _util.AnnotationMode.ENABLE:break;case _util.AnnotationMode.ENABLE_FORMS:n+=_util.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case _util.AnnotationMode.ENABLE_STORAGE:n+=_util.RenderingIntentFlag.ANNOTATIONS_STORAGE;a=(n&_util.RenderingIntentFlag.PRINT&&i instanceof _annotation_storage.PrintAnnotationStorage?i:this.annotationStorage).serializable;break;default:(0,_util.warn)(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(n+=_util.RenderingIntentFlag.OPLIST);return{renderingIntent:n,cacheKey:`${n}_${a.hash}`,annotationStorageSerializable:a}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=new _util.PromiseCapability;this.#u?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#c.values())t.push(e._destroy());this.#c.clear();this.#d.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#h.clear();this.filterFactory.destroy();this._networkStream?.cancelAllRequests(new _util.AbortException("Worker was terminated."));if(this.messageHandler){this.messageHandler.destroy();this.messageHandler=null}this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{(0,_util.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{(0,_util.assert)(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(t=>{const i=new _util.PromiseCapability,s=this._fullReader;s.headersReady.then((()=>{if(!s.isStreamingSupported||!s.isRangeSupported){this._lastProgress&&e.onProgress?.(this._lastProgress);s.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}i.resolve({isStreamingSupported:s.isStreamingSupported,isRangeSupported:s.isRangeSupported,contentLength:s.contentLength})}),i.reject);return i.promise}));t.on("GetRangeReader",((t,e)=>{(0,_util.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{(0,_util.assert)(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(function(t){let i;switch(t.name){case"PasswordException":i=new _util.PasswordException(t.message,t.code);break;case"InvalidPDFException":i=new _util.InvalidPDFException(t.message);break;case"MissingPDFException":i=new _util.MissingPDFException(t.message);break;case"UnexpectedResponseException":i=new _util.UnexpectedResponseException(t.message,t.status);break;case"UnknownErrorException":i=new _util.UnknownErrorException(t.message,t.details);break;default:(0,_util.unreachable)("DocException - expected a valid Error.")}e._capability.reject(i)}));t.on("PasswordRequest",(t=>{this.#u=new _util.PromiseCapability;if(e.onPassword){const updatePassword=t=>{t instanceof Error?this.#u.reject(t):this.#u.resolve({password:t})};try{e.onPassword(updatePassword,t.code)}catch(t){this.#u.reject(t)}}else this.#u.reject(new _util.PasswordException(t.message,t.code));return this.#u.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#c.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(!this.destroyed&&!this.commonObjs.has(e))switch(i){case"Font":const n=this._params;if("error"in s){const t=s.error;(0,_util.warn)(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const a=n.pdfBug&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,r=new _font_loader.FontFaceObject(s,{isEvalSupported:n.isEvalSupported,disableFontFace:n.disableFontFace,ignoreErrors:n.ignoreErrors,inspectFont:a});this.fontLoader.bind(r).catch((i=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!n.fontExtraProperties&&r.data&&(r.data=null);this.commonObjs.resolve(e,r)}));break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#c.get(e);if(!n.objs.has(t))switch(i){case"Image":n.objs.resolve(t,s);if(s){let t;if(s.bitmap){const{width:e,height:i}=s;t=e*i*4}else t=s.data?.length||0;t>_util.MAX_IMAGE_SIZE_TO_CACHE&&(n._maybeCleanupAfterRender=!0)}break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.cMapReaderFactory?this.cMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))));t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.standardFontDataFactory?this.standardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,_util.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfers:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#d.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((t=>{if(this.destroyed)throw new Error("Transport destroyed");const i=new PDFPageProxy(e,t,this,this._params.pdfBug);this.#c.set(e,i);return i}));this.#d.set(e,s);return s}getPageIndex(t){return"object"!=typeof t||null===t||!Number.isInteger(t.num)||t.num<0||!Number.isInteger(t.gen)||t.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen})}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#p("GetFieldObjects")}hasJSActions(){return this.#p("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#p("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(){return this.messageHandler.sendWithPromise("GetOptionalContentConfig",null).then((t=>new _optional_content_config.OptionalContentConfig(t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#h.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new _metadata.Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#h.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#c.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#h.clear();this.filterFactory.destroy(!0)}}get loadingParams(){const{disableAutoFetch:t,enableXfa:e}=this._params;return(0,_util.shadow)(this,"loadingParams",{disableAutoFetch:t,enableXfa:e})}}class PDFObjects{#g=Object.create(null);#m(t){return this.#g[t]||={capability:new _util.PromiseCapability,data:null}}get(t,e=null){if(e){const i=this.#m(t);i.capability.promise.then((()=>e(i.data)));return null}const i=this.#g[t];if(!i?.capability.settled)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#g[t];return e?.capability.settled||!1}resolve(t,e=null){const i=this.#m(t);i.data=e;i.capability.resolve()}clear(){for(const t in this.#g){const{data:e}=this.#g[t];e?.bitmap?.close()}this.#g=Object.create(null)}}class RenderTask{#f=null;constructor(t){this.#f=t;this.onContinue=null}get promise(){return this.#f.capability.promise}cancel(t=0){this.#f.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#f.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#f;return t.form||t.canvas&&e?.size>0}}exports.RenderTask=RenderTask;class InternalRenderTask{static#b=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:a,pageIndex:r,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=c;this.pageColors=d;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=new _util.PromiseCapability;this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#b.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#b.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:a}=this.params;this.gfx=new _canvas.CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();InternalRenderTask.#b.delete(this._canvas);this.callback(t||new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#b.delete(this._canvas);this.callback()}}}}}const version="3.11.174";exports.version=version;const build="ce8716743";exports.build=build},(t,e,i)=>{Object.defineProperty(e,"__esModule",{value:!0});e.SerializableEmpty=e.PrintAnnotationStorage=e.AnnotationStorage=void 0;var s=i(1),n=i(4),a=i(8);const r=Object.freeze({map:null,hash:"",transfers:void 0});e.SerializableEmpty=r;class AnnotationStorage{#A=!1;#_=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#_.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#_.get(t)}remove(t){this.#_.delete(t);0===this.#_.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#_.values())if(t instanceof n.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#_.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#_.set(t,e)}s&&this.#v();e instanceof n.AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#_.has(t)}getAll(){return this.#_.size>0?(0,s.objectFromMap)(this.#_):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#_.size}#v(){if(!this.#A){this.#A=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#A){this.#A=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#_.size)return r;const t=new Map,e=new a.MurmurHash3_64,i=[],s=Object.create(null);let o=!1;for(const[i,a]of this.#_){const r=a instanceof n.AnnotationEditor?a.serialize(!1,s):a;if(r){t.set(i,r);e.update(`${i}:${JSON.stringify(r)}`);o||=!!r.bitmap}}if(o)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfers:i}:r}}e.AnnotationStorage=AnnotationStorage;class PrintAnnotationStorage extends AnnotationStorage{#y;constructor(t){super();const{map:e,hash:i,transfers:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#y={map:n,hash:i,transfers:s}}get print(){(0,s.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#y}}e.PrintAnnotationStorage=PrintAnnotationStorage},(t,e,i)=>{Object.defineProperty(e,"__esModule",{value:!0});e.AnnotationEditor=void 0;var s=i(5),n=i(1),a=i(6);class AnnotationEditor{#S="";#E=!1;#x=null;#w=null;#C=null;#T=!1;#P=null;#M=this.focusin.bind(this);#k=this.focusout.bind(this);#F=!1;#R=!1;#D=!1;_initialOptions=Object.create(null);_uiManager=null;_focusEventsAllowed=!0;_l10nPromise=null;#I=!1;#L=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new s.ColorManager;static _zIndex=1;static SMALL_EDITOR_SIZE=0;constructor(t){this.constructor===AnnotationEditor&&(0,n.unreachable)("Cannot initialize AnnotationEditor.");this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:a,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[a,r];const[o,l]=this.parentDimensions;this.x=t.x/o;this.y=t.y/l;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return(0,n.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e=null){AnnotationEditor._l10nPromise||=new Map(["editor_alt_text_button_label","editor_alt_text_edit_button_label","editor_alt_text_decorative_tooltip"].map((e=>[e,t.get(e)])));if(e?.strings)for(const i of e.strings)AnnotationEditor._l10nPromise.set(i,t.get(i));if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){(0,n.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#I}set _isDraggable(t){this.#I=t;this.div?.classList.toggle("draggable",t)}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#L}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#F?this.#F=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,a]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/a;this.fixAndSetPosition()}#O([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this.fixAndSetPosition()}translate(t,e){this.#O(this.parentDimensions,t,e)}translateInPage(t,e){this.#O(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){const[i,s]=this.parentDimensions;this.x+=t/i;this.y+=e/s;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:n,y:a}=this;const[r,o]=this.#N();n+=r;a+=o;this.div.style.left=`${(100*n).toFixed(2)}%`;this.div.style.top=`${(100*a).toFixed(2)}%`;this.div.scrollIntoView({block:"nearest"})}#N(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}fixAndSetPosition(){const[t,e]=this.pageDimensions;let{x:i,y:s,width:n,height:a}=this;n*=t;a*=e;i*=t;s*=e;switch(this.rotation){case 0:i=Math.max(0,Math.min(t-n,i));s=Math.max(0,Math.min(e-a,s));break;case 90:i=Math.max(0,Math.min(t-a,i));s=Math.min(e,Math.max(n,s));break;case 180:i=Math.min(t,Math.max(n,i));s=Math.min(e,Math.max(a,s));break;case 270:i=Math.min(t,Math.max(a,i));s=Math.max(0,Math.min(e-n,s))}this.x=i/=t;this.y=s/=e;const[r,o]=this.#N();i+=r;s+=o;const{style:l}=this.div;l.left=`${(100*i).toFixed(2)}%`;l.top=`${(100*s).toFixed(2)}%`;this.moveInDOM()}static#B(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#B(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#B(t,e,360-this.parentRotation)}#U(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this,s=e*t,a=i*t;return n.FeatureTest.isCSSRoundSupported?[Math.round(s),Math.round(a)]:[s,a]}setDims(t,e){const[i,s]=this.parentDimensions;this.div.style.width=`${(100*t/i).toFixed(2)}%`;this.#T||(this.div.style.height=`${(100*e/s).toFixed(2)}%`);this.#x?.classList.toggle("small",t>8]>>8:e[n]*s>>16}}function composeSMask(t,e,i,s){const n=s[0],a=s[1],r=s[2]-n,o=s[3]-a;if(0!==r&&0!==o){!function genericComposeSMask(t,e,i,s,n,a,r,o,l,h,c){const d=!!a,u=d?a[0]:0,p=d?a[1]:0,g=d?a[2]:0,m="Luminosity"===n?composeSMaskLuminosity:composeSMaskAlpha,f=Math.min(s,Math.ceil(1048576/i));for(let n=0;n10&&"function"==typeof i,c=h?Date.now()+15:0;let d=0;const u=this.commonObjs,p=this.objs;let g;for(;;){if(void 0!==n&&o===n.nextBreakPoint){n.breakIt(o,i);return o}g=r[o];if(g!==s.OPS.dependency)this[g].apply(this,a[o]);else for(const t of a[o]){const e=t.startsWith("g_")?u:p;if(!e.has(t)){e.get(t,i);return o}}o++;if(o===l)return o;if(h&&++d>10){if(Date.now()>c){i();return o}d=0}}}#he(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#he();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#ce()}#ce(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width,s=t.height;let n,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,c="prescale1";for(;r>2&&l>1||o>2&&h>1;){let e=l,i=h;if(r>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);r/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(c,e,i);a=n.context;a.clearRect(0,0,e,i);a.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:r}=t,o=this.current.fillColor,l=this.current.patternFill,h=(0,n.getCurrentTransform)(e);let c,d,u,p;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;d=JSON.stringify(l?h:[h.slice(0,4),o]);c=this._cachedBitmapsMap.get(e);if(!c){c=new Map;this._cachedBitmapsMap.set(e,c)}const i=c.get(d);if(i&&!l){return{canvas:i,offsetX:Math.round(Math.min(h[0],h[2])+h[4]),offsetY:Math.round(Math.min(h[1],h[3])+h[5])}}u=i}if(!u){p=this.cachedCanvases.getCanvas("maskCanvas",i,r);putBinaryImageMask(p.context,t)}let g=s.Util.transform(h,[1/i,0,0,-1/r,0,0]);g=s.Util.transform(g,[1,0,0,1,0,-r]);const m=s.Util.applyTransform([0,0],g),f=s.Util.applyTransform([i,r],g),b=s.Util.normalizeRect([m[0],m[1],f[0],f[1]]),A=Math.round(b[2]-b[0])||1,_=Math.round(b[3]-b[1])||1,v=this.cachedCanvases.getCanvas("fillCanvas",A,_),y=v.context,S=Math.min(m[0],f[0]),E=Math.min(m[1],f[1]);y.translate(-S,-E);y.transform(...g);if(!u){u=this._scaleImage(p.canvas,(0,n.getCurrentTransformInverse)(y));u=u.img;c&&l&&c.set(d,u)}y.imageSmoothingEnabled=getImageSmoothingEnabled((0,n.getCurrentTransform)(y),t.interpolate);drawImageAtIntegerCoords(y,u,0,0,u.width,u.height,0,0,i,r);y.globalCompositeOperation="source-in";const x=s.Util.transform((0,n.getCurrentTransformInverse)(y),[1,0,0,1,-S,-E]);y.fillStyle=l?o.getPattern(e,this,x,a.PathType.FILL):o;y.fillRect(0,0,i,r);if(c&&!l){this.cachedCanvases.delete("fillCanvas");c.set(d,v.canvas)}return{canvas:v.canvas,offsetX:Math.round(S),offsetY:Math.round(E)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=h[t]}setLineJoin(t){this.ctx.lineJoin=c[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const a=this.ctx;a.setTransform(...(0,n.getCurrentTransform)(this.suspendedCtx));copyCtxState(this.suspendedCtx,a);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,a,r){e.transform(t,i,s,n,a,r);this.__originalTransform(t,i,s,n,a,r)};t.setTransform=function ctxSetTransform(t,i,s,n,a,r){e.setTransform(t,i,s,n,a,r);this.__originalSetTransform(t,i,s,n,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,a,r){e.bezierCurveTo(t,i,s,n,a,r);this.__originalBezierCurveTo(t,i,s,n,a,r)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(a,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask;composeSMask(this.suspendedCtx,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,a){this.ctx.transform(t,e,i,s,n,a);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const a=this.ctx,r=this.current;let o,l,h=r.x,c=r.y;const d=(0,n.getCurrentTransform)(a),u=0===d[0]&&0===d[3]||0===d[1]&&0===d[2],p=u?i.slice(0):null;for(let i=0,n=0,g=t.length;i>>8|255;i[n+2]=e<<16|s>>>16|255;i[n+3]=s<<8|255}for(let e=4*o,s=t.length;e>3,u=7&n,p=t.length;i=new Uint32Array(i.buffer);let g=0;for(let s=0;s{Object.defineProperty(e,"__esModule",{value:!0});e.GlobalWorkerOptions=void 0;const i=Object.create(null);e.GlobalWorkerOptions=i;i.workerPort=null;i.workerSrc=""},(t,e,i)=>{Object.defineProperty(e,"__esModule",{value:!0});e.MessageHandler=void 0;var s=i(1);const n=1,a=2,r=1,o=2,l=3,h=4,c=5,d=6,u=7,p=8;function wrapReason(t){t instanceof Error||"object"==typeof t&&null!==t||(0,s.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new s.AbortException(t.message);case"MissingPDFException":return new s.MissingPDFException(t.message);case"PasswordException":return new s.PasswordException(t.message,t.code);case"UnexpectedResponseException":return new s.UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new s.UnknownErrorException(t.message,t.details);default:return new s.UnknownErrorException(t.message,t.toString())}}e.MessageHandler=class MessageHandler{constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);this._onComObjOnMessage=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream){this.#de(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===n)i.resolve(e.data);else{if(e.callback!==a)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const s=this.actionHandler[e.action];if(!s)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,r=e.sourceName;new Promise((function(t){t(s(e.data))})).then((function(s){i.postMessage({sourceName:t,targetName:r,callback:n,callbackId:e.callbackId,data:s})}),(function(s){i.postMessage({sourceName:t,targetName:r,callback:a,callbackId:e.callbackId,reason:wrapReason(s)})}))}else e.streamId?this.#ue(e):s(e.data)};i.addEventListener("message",this._onComObjOnMessage)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const n=this.callbackId++,a=new s.PromiseCapability;this.callbackCapabilities[n]=a;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:n,data:e},i)}catch(t){a.reject(t)}return a.promise}sendWithStream(t,e,i,n){const a=this.streamId++,o=this.sourceName,l=this.targetName,h=this.comObj;return new ReadableStream({start:i=>{const r=new s.PromiseCapability;this.streamControllers[a]={controller:i,startCall:r,pullCall:null,cancelCall:null,isClosed:!1};h.postMessage({sourceName:o,targetName:l,action:t,streamId:a,data:e,desiredSize:i.desiredSize},n);return r.promise},pull:t=>{const e=new s.PromiseCapability;this.streamControllers[a].pullCall=e;h.postMessage({sourceName:o,targetName:l,stream:d,streamId:a,desiredSize:t.desiredSize});return e.promise},cancel:t=>{(0,s.assert)(t instanceof Error,"cancel must have a valid reason");const e=new s.PromiseCapability;this.streamControllers[a].cancelCall=e;this.streamControllers[a].isClosed=!0;h.postMessage({sourceName:o,targetName:l,stream:r,streamId:a,reason:wrapReason(t)});return e.promise}},i)}#ue(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,a=this.comObj,r=this,o=this.actionHandler[t.action],d={enqueue(t,r=1,o){if(this.isCancelled)return;const l=this.desiredSize;this.desiredSize-=r;if(l>0&&this.desiredSize<=0){this.sinkCapability=new s.PromiseCapability;this.ready=this.sinkCapability.promise}a.postMessage({sourceName:i,targetName:n,stream:h,streamId:e,chunk:t},o)},close(){if(!this.isCancelled){this.isCancelled=!0;a.postMessage({sourceName:i,targetName:n,stream:l,streamId:e});delete r.streamSinks[e]}},error(t){(0,s.assert)(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;a.postMessage({sourceName:i,targetName:n,stream:c,streamId:e,reason:wrapReason(t)})}},sinkCapability:new s.PromiseCapability,onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};d.sinkCapability.resolve();d.ready=d.sinkCapability.promise;this.streamSinks[e]=d;new Promise((function(e){e(o(t.data,d))})).then((function(){a.postMessage({sourceName:i,targetName:n,stream:p,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:i,targetName:n,stream:p,streamId:e,reason:wrapReason(t)})}))}#de(t){const e=t.streamId,i=this.sourceName,n=t.sourceName,a=this.comObj,g=this.streamControllers[e],m=this.streamSinks[e];switch(t.stream){case p:t.success?g.startCall.resolve():g.startCall.reject(wrapReason(t.reason));break;case u:t.success?g.pullCall.resolve():g.pullCall.reject(wrapReason(t.reason));break;case d:if(!m){a.postMessage({sourceName:i,targetName:n,stream:u,streamId:e,success:!0});break}m.desiredSize<=0&&t.desiredSize>0&&m.sinkCapability.resolve();m.desiredSize=t.desiredSize;new Promise((function(t){t(m.onPull?.())})).then((function(){a.postMessage({sourceName:i,targetName:n,stream:u,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:i,targetName:n,stream:u,streamId:e,reason:wrapReason(t)})}));break;case h:(0,s.assert)(g,"enqueue should have stream controller");if(g.isClosed)break;g.controller.enqueue(t.chunk);break;case l:(0,s.assert)(g,"close should have stream controller");if(g.isClosed)break;g.isClosed=!0;g.controller.close();this.#pe(g,e);break;case c:(0,s.assert)(g,"error should have stream controller");g.controller.error(wrapReason(t.reason));this.#pe(g,e);break;case o:t.success?g.cancelCall.resolve():g.cancelCall.reject(wrapReason(t.reason));this.#pe(g,e);break;case r:if(!m)break;new Promise((function(e){e(m.onCancel?.(wrapReason(t.reason)))})).then((function(){a.postMessage({sourceName:i,targetName:n,stream:o,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:i,targetName:n,stream:o,streamId:e,reason:wrapReason(t)})}));m.sinkCapability.reject(wrapReason(t.reason));m.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#pe(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},(t,e,i)=>{Object.defineProperty(e,"__esModule",{value:!0});e.Metadata=void 0;var s=i(1);e.Metadata=class Metadata{#ge;#me;constructor({parsedData:t,rawData:e}){this.#ge=t;this.#me=e}getRaw(){return this.#me}get(t){return this.#ge.get(t)??null}getAll(){return(0,s.objectFromMap)(this.#ge)}has(t){return this.#ge.has(t)}}},(t,e,i)=>{Object.defineProperty(e,"__esModule",{value:!0});e.OptionalContentConfig=void 0;var s=i(1),n=i(8);const a=Symbol("INTERNAL");class OptionalContentGroup{#fe=!0;constructor(t,e){this.name=t;this.intent=e}get visible(){return this.#fe}_setVisible(t,e){t!==a&&(0,s.unreachable)("Internal method `_setVisible` called.");this.#fe=e}}e.OptionalContentConfig=class OptionalContentConfig{#be=null;#Ae=new Map;#_e=null;#ve=null;constructor(t){this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#ve=t.order;for(const e of t.groups)this.#Ae.set(e.id,new OptionalContentGroup(e.name,e.intent));if("OFF"===t.baseState)for(const t of this.#Ae.values())t._setVisible(a,!1);for(const e of t.on)this.#Ae.get(e)._setVisible(a,!0);for(const e of t.off)this.#Ae.get(e)._setVisible(a,!1);this.#_e=this.getHash()}}#ye(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let n=1;n>>8^e[i]}return-1^n}(s,n+4,a);s[a]=o>>24&255;s[a+1]=o>>16&255;s[a+2]=o>>8&255;s[a+3]=255&o}function deflateSyncUncompressed(t){let e=t.length;const i=65535,s=Math.ceil(e/i),n=new Uint8Array(2+e+5*s+4);let a=0;n[a++]=120;n[a++]=156;let r=0;for(;e>i;){n[a++]=0;n[a++]=255;n[a++]=255;n[a++]=0;n[a++]=0;n.set(t.subarray(r,r+i),a);a+=i;r+=i;e-=i}n[a++]=1;n[a++]=255&e;n[a++]=e>>8&255;n[a++]=255&~e;n[a++]=(65535&~e)>>8&255;n.set(t.subarray(r),a);a+=t.length-r;const o=function adler32(t,e,i){let s=1,n=0;for(let a=e;a>24&255;n[a++]=o>>16&255;n[a++]=o>>8&255;n[a++]=255&o;return n}function encode(e,i,s,a){const r=e.width,o=e.height;let l,h,c;const d=e.data;switch(i){case n.ImageKind.GRAYSCALE_1BPP:h=0;l=1;c=r+7>>3;break;case n.ImageKind.RGB_24BPP:h=2;l=8;c=3*r;break;case n.ImageKind.RGBA_32BPP:h=6;l=8;c=4*r;break;default:throw new Error("invalid format")}const u=new Uint8Array((1+c)*o);let p=0,g=0;for(let t=0;t{t.get(e,i)}));this.current.dependencies.push(i)}return Promise.all(this.current.dependencies)}transform(t,e,i,s,a,r){const o=[t,e,i,s,a,r];this.transformMatrix=n.Util.transform(this.transformMatrix,o);this.tgrp=null}getSVG(t,e){this.viewport=e;const i=this._initialize(e);return this.loadDependencies(t).then((()=>{this.transformMatrix=n.IDENTITY_MATRIX;this.executeOpTree(this.convertOpList(t));return i}))}convertOpList(t){const e=this._operatorIdMapping,i=t.argsArray,s=t.fnArray,n=[];for(let t=0,a=s.length;t0&&(this.current.lineWidth=t)}setLineCap(t){this.current.lineCap=l[t]}setLineJoin(t){this.current.lineJoin=h[t]}setMiterLimit(t){this.current.miterLimit=t}setStrokeAlpha(t){this.current.strokeAlpha=t}setStrokeRGBColor(t,e,i){this.current.strokeColor=n.Util.makeHexColor(t,e,i)}setFillAlpha(t){this.current.fillAlpha=t}setFillRGBColor(t,e,i){this.current.fillColor=n.Util.makeHexColor(t,e,i);this.current.tspan=this.svgFactory.createElement("svg:tspan");this.current.xcoords=[];this.current.ycoords=[]}setStrokeColorN(t){this.current.strokeColor=this._makeColorN_Pattern(t)}setFillColorN(t){this.current.fillColor=this._makeColorN_Pattern(t)}shadingFill(t){const{width:e,height:i}=this.viewport,s=n.Util.inverseTransform(this.transformMatrix),[a,r,o,l]=n.Util.getAxialAlignedBoundingBox([0,0,e,i],s),h=this.svgFactory.createElement("svg:rect");h.setAttributeNS(null,"x",a);h.setAttributeNS(null,"y",r);h.setAttributeNS(null,"width",o-a);h.setAttributeNS(null,"height",l-r);h.setAttributeNS(null,"fill",this._makeShadingPattern(t));this.current.fillAlpha<1&&h.setAttributeNS(null,"fill-opacity",this.current.fillAlpha);this._ensureTransformGroup().append(h)}_makeColorN_Pattern(t){return"TilingPattern"===t[0]?this._makeTilingPattern(t):this._makeShadingPattern(t)}_makeTilingPattern(t){const e=t[1],i=t[2],s=t[3]||n.IDENTITY_MATRIX,[a,r,o,l]=t[4],h=t[5],c=t[6],d=t[7],u="shading"+p++,[g,m,f,b]=n.Util.normalizeRect([...n.Util.applyTransform([a,r],s),...n.Util.applyTransform([o,l],s)]),[A,_]=n.Util.singularValueDecompose2dScale(s),v=h*A,y=c*_,S=this.svgFactory.createElement("svg:pattern");S.setAttributeNS(null,"id",u);S.setAttributeNS(null,"patternUnits","userSpaceOnUse");S.setAttributeNS(null,"width",v);S.setAttributeNS(null,"height",y);S.setAttributeNS(null,"x",`${g}`);S.setAttributeNS(null,"y",`${m}`);const E=this.svg,x=this.transformMatrix,w=this.current.fillColor,C=this.current.strokeColor,T=this.svgFactory.create(f-g,b-m);this.svg=T;this.transformMatrix=s;if(2===d){const t=n.Util.makeHexColor(...e);this.current.fillColor=t;this.current.strokeColor=t}this.executeOpTree(this.convertOpList(i));this.svg=E;this.transformMatrix=x;this.current.fillColor=w;this.current.strokeColor=C;S.append(T.childNodes[0]);this.defs.append(S);return`url(#${u})`}_makeShadingPattern(t){"string"==typeof t&&(t=this.objs.get(t));switch(t[0]){case"RadialAxial":const e="shading"+p++,i=t[3];let s;switch(t[1]){case"axial":const i=t[4],n=t[5];s=this.svgFactory.createElement("svg:linearGradient");s.setAttributeNS(null,"id",e);s.setAttributeNS(null,"gradientUnits","userSpaceOnUse");s.setAttributeNS(null,"x1",i[0]);s.setAttributeNS(null,"y1",i[1]);s.setAttributeNS(null,"x2",n[0]);s.setAttributeNS(null,"y2",n[1]);break;case"radial":const a=t[4],r=t[5],o=t[6],l=t[7];s=this.svgFactory.createElement("svg:radialGradient");s.setAttributeNS(null,"id",e);s.setAttributeNS(null,"gradientUnits","userSpaceOnUse");s.setAttributeNS(null,"cx",r[0]);s.setAttributeNS(null,"cy",r[1]);s.setAttributeNS(null,"r",l);s.setAttributeNS(null,"fx",a[0]);s.setAttributeNS(null,"fy",a[1]);s.setAttributeNS(null,"fr",o);break;default:throw new Error(`Unknown RadialAxial type: ${t[1]}`)}for(const t of i){const e=this.svgFactory.createElement("svg:stop");e.setAttributeNS(null,"offset",t[0]);e.setAttributeNS(null,"stop-color",t[1]);s.append(e)}this.defs.append(s);return`url(#${e})`;case"Mesh":(0,n.warn)("Unimplemented pattern Mesh");return null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${t[0]}`)}}setDash(t,e){this.current.dashArray=t;this.current.dashPhase=e}constructPath(t,e){const i=this.current;let s=i.x,a=i.y,r=[],o=0;for(const i of t)switch(0|i){case n.OPS.rectangle:s=e[o++];a=e[o++];const t=s+e[o++],i=a+e[o++];r.push("M",pf(s),pf(a),"L",pf(t),pf(a),"L",pf(t),pf(i),"L",pf(s),pf(i),"Z");break;case n.OPS.moveTo:s=e[o++];a=e[o++];r.push("M",pf(s),pf(a));break;case n.OPS.lineTo:s=e[o++];a=e[o++];r.push("L",pf(s),pf(a));break;case n.OPS.curveTo:s=e[o+4];a=e[o+5];r.push("C",pf(e[o]),pf(e[o+1]),pf(e[o+2]),pf(e[o+3]),pf(s),pf(a));o+=6;break;case n.OPS.curveTo2:r.push("C",pf(s),pf(a),pf(e[o]),pf(e[o+1]),pf(e[o+2]),pf(e[o+3]));s=e[o+2];a=e[o+3];o+=4;break;case n.OPS.curveTo3:s=e[o+2];a=e[o+3];r.push("C",pf(e[o]),pf(e[o+1]),pf(s),pf(a),pf(s),pf(a));o+=4;break;case n.OPS.closePath:r.push("Z")}r=r.join(" ");if(i.path&&t.length>0&&t[0]!==n.OPS.rectangle&&t[0]!==n.OPS.moveTo)r=i.path.getAttributeNS(null,"d")+r;else{i.path=this.svgFactory.createElement("svg:path");this._ensureTransformGroup().append(i.path)}i.path.setAttributeNS(null,"d",r);i.path.setAttributeNS(null,"fill","none");i.element=i.path;i.setCurrentPoint(s,a)}endPath(){const t=this.current;t.path=null;if(!this.pendingClip)return;if(!t.element){this.pendingClip=null;return}const e="clippath"+d++,i=this.svgFactory.createElement("svg:clipPath");i.setAttributeNS(null,"id",e);i.setAttributeNS(null,"transform",pm(this.transformMatrix));const s=t.element.cloneNode(!0);"evenodd"===this.pendingClip?s.setAttributeNS(null,"clip-rule","evenodd"):s.setAttributeNS(null,"clip-rule","nonzero");this.pendingClip=null;i.append(s);this.defs.append(i);if(t.activeClipUrl){t.clipGroup=null;for(const t of this.extraStack)t.clipGroup=null;i.setAttributeNS(null,"clip-path",t.activeClipUrl)}t.activeClipUrl=`url(#${e})`;this.tgrp=null}clip(t){this.pendingClip=t}closePath(){const t=this.current;if(t.path){const e=`${t.path.getAttributeNS(null,"d")}Z`;t.path.setAttributeNS(null,"d",e)}}setLeading(t){this.current.leading=-t}setTextRise(t){this.current.textRise=t}setTextRenderingMode(t){this.current.textRenderingMode=t}setHScale(t){this.current.textHScale=t/100}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i);break;case"CA":this.setStrokeAlpha(i);break;case"ca":this.setFillAlpha(i);break;default:(0,n.warn)(`Unimplemented graphic state operator ${e}`)}}fill(){const t=this.current;if(t.element){t.element.setAttributeNS(null,"fill",t.fillColor);t.element.setAttributeNS(null,"fill-opacity",t.fillAlpha);this.endPath()}}stroke(){const t=this.current;if(t.element){this._setStrokeAttributes(t.element);t.element.setAttributeNS(null,"fill","none");this.endPath()}}_setStrokeAttributes(t,e=1){const i=this.current;let s=i.dashArray;1!==e&&s.length>0&&(s=s.map((function(t){return e*t})));t.setAttributeNS(null,"stroke",i.strokeColor);t.setAttributeNS(null,"stroke-opacity",i.strokeAlpha);t.setAttributeNS(null,"stroke-miterlimit",pf(i.miterLimit));t.setAttributeNS(null,"stroke-linecap",i.lineCap);t.setAttributeNS(null,"stroke-linejoin",i.lineJoin);t.setAttributeNS(null,"stroke-width",pf(e*i.lineWidth)+"px");t.setAttributeNS(null,"stroke-dasharray",s.map(pf).join(" "));t.setAttributeNS(null,"stroke-dashoffset",pf(e*i.dashPhase)+"px")}eoFill(){this.current.element?.setAttributeNS(null,"fill-rule","evenodd");this.fill()}fillStroke(){this.stroke();this.fill()}eoFillStroke(){this.current.element?.setAttributeNS(null,"fill-rule","evenodd");this.fillStroke()}closeStroke(){this.closePath();this.stroke()}closeFillStroke(){this.closePath();this.fillStroke()}closeEOFillStroke(){this.closePath();this.eoFillStroke()}paintSolidColorImageMask(){const t=this.svgFactory.createElement("svg:rect");t.setAttributeNS(null,"x","0");t.setAttributeNS(null,"y","0");t.setAttributeNS(null,"width","1px");t.setAttributeNS(null,"height","1px");t.setAttributeNS(null,"fill",this.current.fillColor);this._ensureTransformGroup().append(t)}paintImageXObject(t){const e=this.getObject(t);e?this.paintInlineImageXObject(e):(0,n.warn)(`Dependent image with object ID ${t} is not ready yet`)}paintInlineImageXObject(t,e){const i=t.width,s=t.height,n=c(t,this.forceDataSchema,!!e),a=this.svgFactory.createElement("svg:rect");a.setAttributeNS(null,"x","0");a.setAttributeNS(null,"y","0");a.setAttributeNS(null,"width",pf(i));a.setAttributeNS(null,"height",pf(s));this.current.element=a;this.clip("nonzero");const r=this.svgFactory.createElement("svg:image");r.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n);r.setAttributeNS(null,"x","0");r.setAttributeNS(null,"y",pf(-s));r.setAttributeNS(null,"width",pf(i)+"px");r.setAttributeNS(null,"height",pf(s)+"px");r.setAttributeNS(null,"transform",`scale(${pf(1/i)} ${pf(-1/s)})`);e?e.append(r):this._ensureTransformGroup().append(r)}paintImageMaskXObject(t){const e=this.getObject(t.data,t);if(e.bitmap){(0,n.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");return}const i=this.current,s=e.width,a=e.height,r=i.fillColor;i.maskId="mask"+u++;const o=this.svgFactory.createElement("svg:mask");o.setAttributeNS(null,"id",i.maskId);const l=this.svgFactory.createElement("svg:rect");l.setAttributeNS(null,"x","0");l.setAttributeNS(null,"y","0");l.setAttributeNS(null,"width",pf(s));l.setAttributeNS(null,"height",pf(a));l.setAttributeNS(null,"fill",r);l.setAttributeNS(null,"mask",`url(#${i.maskId})`);this.defs.append(o);this._ensureTransformGroup().append(l);this.paintInlineImageXObject(e,o)}paintFormXObjectBegin(t,e){Array.isArray(t)&&6===t.length&&this.transform(t[0],t[1],t[2],t[3],t[4],t[5]);if(e){const t=e[2]-e[0],i=e[3]-e[1],s=this.svgFactory.createElement("svg:rect");s.setAttributeNS(null,"x",e[0]);s.setAttributeNS(null,"y",e[1]);s.setAttributeNS(null,"width",pf(t));s.setAttributeNS(null,"height",pf(i));this.current.element=s;this.clip("nonzero");this.endPath()}}paintFormXObjectEnd(){}_initialize(t){const e=this.svgFactory.create(t.width,t.height),i=this.svgFactory.createElement("svg:defs");e.append(i);this.defs=i;const s=this.svgFactory.createElement("svg:g");s.setAttributeNS(null,"transform",pm(t.transform));e.append(s);this.svg=s;return e}_ensureClipGroup(){if(!this.current.clipGroup){const t=this.svgFactory.createElement("svg:g");t.setAttributeNS(null,"clip-path",this.current.activeClipUrl);this.svg.append(t);this.current.clipGroup=t}return this.current.clipGroup}_ensureTransformGroup(){if(!this.tgrp){this.tgrp=this.svgFactory.createElement("svg:g");this.tgrp.setAttributeNS(null,"transform",pm(this.transformMatrix));this.current.activeClipUrl?this._ensureClipGroup().append(this.tgrp):this.svg.append(this.tgrp)}return this.tgrp}}},(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});e.XfaText=void 0;class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}e.XfaText=XfaText},(t,e,i)=>{Object.defineProperty(e,"__esModule",{value:!0});e.TextLayerRenderTask=void 0;e.renderTextLayer=function renderTextLayer(t){if(!t.textContentSource&&(t.textContent||t.textContentStream)){(0,n.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters will be removed in the future, please use `textContentSource` instead.");t.textContentSource=t.textContent||t.textContentStream}const{container:e,viewport:i}=t,s=getComputedStyle(e),a=s.getPropertyValue("visibility"),r=parseFloat(s.getPropertyValue("--scale-factor"));"visible"===a&&(!r||Math.abs(r-i.scale)>1e-5)&&console.error("The `--scale-factor` CSS-variable must be set, to the same value as `viewport.scale`, either on the `container`-element itself or higher up in the DOM.");const o=new TextLayerRenderTask(t);o._render();return o};e.updateTextLayer=function updateTextLayer({container:t,viewport:e,textDivs:i,textDivProperties:s,isOffscreenCanvasSupported:a,mustRotate:r=!0,mustRescale:o=!0}){r&&(0,n.setLayerDimensions)(t,{rotation:e.rotation});if(o){const t=getCtx(0,a),n={prevFontSize:null,prevFontFamily:null,div:null,scale:e.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:t};for(const t of i){n.properties=s.get(t);n.div=t;layout(n)}}};var s=i(1),n=i(6);const a=30,r=.8,o=new Map;function getCtx(t,e){let i;if(e&&s.FeatureTest.isOffscreenCanvasSupported)i=new OffscreenCanvas(t,t).getContext("2d",{alpha:!1});else{const e=document.createElement("canvas");e.width=e.height=t;i=e.getContext("2d",{alpha:!1})}return i}function appendText(t,e,i){const n=document.createElement("span"),l={angle:0,canvasWidth:0,hasText:""!==e.str,hasEOL:e.hasEOL,fontSize:0};t._textDivs.push(n);const h=s.Util.transform(t._transform,e.transform);let c=Math.atan2(h[1],h[0]);const d=i[e.fontName];d.vertical&&(c+=Math.PI/2);const u=Math.hypot(h[2],h[3]),p=u*function getAscent(t,e){const i=o.get(t);if(i)return i;const s=getCtx(a,e);s.font=`${a}px ${t}`;const n=s.measureText("");let l=n.fontBoundingBoxAscent,h=Math.abs(n.fontBoundingBoxDescent);if(l){const e=l/(l+h);o.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,a,a);s.strokeText("g",0,0);let c=s.getImageData(0,0,a,a).data;h=0;for(let t=c.length-1-3;t>=0;t-=4)if(c[t]>0){h=Math.ceil(t/4/a);break}s.clearRect(0,0,a,a);s.strokeText("A",0,a);c=s.getImageData(0,0,a,a).data;l=0;for(let t=0,e=c.length;t{Object.defineProperty(e,"__esModule",{value:!0});e.StampEditor=void 0;var s=i(1),n=i(4),a=i(6),r=i(29);class StampEditor extends n.AnnotationEditor{#fs=null;#bs=null;#As=null;#_s=null;#vs=null;#ys=null;#zi=null;#Ss=null;#Es=!1;#xs=!1;static _type="stamp";constructor(t){super({...t,name:"stampEditor"});this.#_s=t.bitmapUrl;this.#vs=t.bitmapFile}static initialize(t){n.AnnotationEditor.initialize(t)}static get supportedTypes(){return(0,s.shadow)(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return(0,s.shadow)(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(s.AnnotationEditorType.STAMP,{bitmapFile:t.getAsFile()})}#ws(t,e=!1){if(t){this.#fs=t.bitmap;if(!e){this.#bs=t.id;this.#Es=t.isSvg}this.#Ki()}else this.remove()}#Cs(){this.#As=null;this._uiManager.enableWaiting(!1);this.#ys&&this.div.focus()}#Ts(){if(this.#bs){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#bs).then((t=>this.#ws(t,!0))).finally((()=>this.#Cs()));return}if(this.#_s){const t=this.#_s;this.#_s=null;this._uiManager.enableWaiting(!0);this.#As=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#ws(t))).finally((()=>this.#Cs()));return}if(this.#vs){const t=this.#vs;this.#vs=null;this._uiManager.enableWaiting(!0);this.#As=this._uiManager.imageManager.getFromFile(t).then((t=>this.#ws(t))).finally((()=>this.#Cs()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;this.#As=new Promise((e=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this.#ws(e)}else this.remove();e()}));t.addEventListener("cancel",(()=>{this.remove();e()}))})).finally((()=>this.#Cs()));t.click()}remove(){if(this.#bs){this.#fs=null;this._uiManager.imageManager.deleteId(this.#bs);this.#ys?.remove();this.#ys=null;this.#zi?.disconnect();this.#zi=null}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#bs&&this.#Ts();this.isAttachedToDOM||this.parent.add(this)}}else this.#bs&&this.#Ts()}onceAdded(){this._isDraggable=!0;this.div.focus()}isEmpty(){return!(this.#As||this.#fs||this.#_s||this.#vs)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.#fs?this.#Ki():this.#Ts();if(this.width){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}return this.div}#Ki(){const{div:t}=this;let{width:e,height:i}=this.#fs;const[s,n]=this.pageDimensions,a=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>a*s||i>a*n){const t=Math.min(a*s/e,a*n/i);e*=t;i*=t}const[r,o]=this.parentDimensions;this.setDims(e*r/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#ys=document.createElement("canvas");t.append(l);t.hidden=!1;this.#Ps(e,i);this.#Yi();if(!this.#xs){this.parent.addUndoableEditor(this);this.#xs=!0}this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",subtype:this.editorType,data:{action:"inserted_image"}}});this.addAltTextButton()}#Ms(t,e){const[i,s]=this.parentDimensions;this.width=t/i;this.height=e/s;this.setDims(t,e);this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;null!==this.#Ss&&clearTimeout(this.#Ss);this.#Ss=setTimeout((()=>{this.#Ss=null;this.#Ps(t,e)}),200)}#ks(t,e){const{width:i,height:s}=this.#fs;let n=i,a=s,r=this.#fs;for(;n>2*t||a>2*e;){const i=n,s=a;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));a>2*e&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const o=new OffscreenCanvas(n,a);o.getContext("2d").drawImage(r,0,0,i,s,0,0,n,a);r=o.transferToImageBitmap()}return r}#Ps(t,e){t=Math.ceil(t);e=Math.ceil(e);const i=this.#ys;if(!i||i.width===t&&i.height===e)return;i.width=t;i.height=e;const s=this.#Es?this.#fs:this.#ks(t,e),n=i.getContext("2d");n.filter=this._uiManager.hcmFilter;n.drawImage(s,0,0,s.width,s.height,0,0,t,e)}#Fs(t){if(t){if(this.#Es){const t=this._uiManager.imageManager.getSvgUrl(this.#bs);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#fs);t.getContext("2d").drawImage(this.#fs,0,0);return t.toDataURL()}if(this.#Es){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*a.PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*a.PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#fs,0,0,this.#fs.width,this.#fs.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#fs)}#Yi(){this.#zi=new ResizeObserver((t=>{const e=t[0].contentRect;e.width&&e.height&&this.#Ms(e.width,e.height)}));this.#zi.observe(this.div)}static deserialize(t,e,i){if(t instanceof r.StampAnnotationElement)return null;const s=super.deserialize(t,e,i),{rect:n,bitmapUrl:a,bitmapId:o,isSvg:l,accessibilityData:h}=t;o&&i.imageManager.isValidId(o)?s.#bs=o:s.#_s=a;s.#Es=l;const[c,d]=s.pageDimensions;s.width=(n[2]-n[0])/c;s.height=(n[3]-n[1])/d;h&&(s.altTextData=h);return s}serialize(t=!1,e=null){if(this.isEmpty())return null;const i={annotationType:s.AnnotationEditorType.STAMP,bitmapId:this.#bs,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Es,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#Fs(!0);i.accessibilityData=this.altTextData;return i}const{decorative:n,altText:a}=this.altTextData;!n&&a&&(i.accessibilityData={type:"Figure",alt:a});if(null===e)return i;e.stamps||=new Map;const r=this.#Es?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#bs)){if(this.#Es){const t=e.stamps.get(this.#bs);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#Fs(!1)}}}else{e.stamps.set(this.#bs,{area:r,serialized:i});i.bitmap=this.#Fs(!1)}return i}}e.StampEditor=StampEditor}],__webpack_module_cache__={};function __w_pdfjs_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var i=__webpack_module_cache__[t]={exports:{}};__webpack_modules__[t](i,i.exports,__w_pdfjs_require__);return i.exports}var __webpack_exports__={};(()=>{var t=__webpack_exports__;Object.defineProperty(t,"__esModule",{value:!0});Object.defineProperty(t,"AbortException",{enumerable:!0,get:function(){return e.AbortException}});Object.defineProperty(t,"AnnotationEditorLayer",{enumerable:!0,get:function(){return a.AnnotationEditorLayer}});Object.defineProperty(t,"AnnotationEditorParamsType",{enumerable:!0,get:function(){return e.AnnotationEditorParamsType}});Object.defineProperty(t,"AnnotationEditorType",{enumerable:!0,get:function(){return e.AnnotationEditorType}});Object.defineProperty(t,"AnnotationEditorUIManager",{enumerable:!0,get:function(){return r.AnnotationEditorUIManager}});Object.defineProperty(t,"AnnotationLayer",{enumerable:!0,get:function(){return o.AnnotationLayer}});Object.defineProperty(t,"AnnotationMode",{enumerable:!0,get:function(){return e.AnnotationMode}});Object.defineProperty(t,"CMapCompressionType",{enumerable:!0,get:function(){return e.CMapCompressionType}});Object.defineProperty(t,"DOMSVGFactory",{enumerable:!0,get:function(){return s.DOMSVGFactory}});Object.defineProperty(t,"FeatureTest",{enumerable:!0,get:function(){return e.FeatureTest}});Object.defineProperty(t,"GlobalWorkerOptions",{enumerable:!0,get:function(){return l.GlobalWorkerOptions}});Object.defineProperty(t,"ImageKind",{enumerable:!0,get:function(){return e.ImageKind}});Object.defineProperty(t,"InvalidPDFException",{enumerable:!0,get:function(){return e.InvalidPDFException}});Object.defineProperty(t,"MissingPDFException",{enumerable:!0,get:function(){return e.MissingPDFException}});Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return e.OPS}});Object.defineProperty(t,"PDFDataRangeTransport",{enumerable:!0,get:function(){return i.PDFDataRangeTransport}});Object.defineProperty(t,"PDFDateString",{enumerable:!0,get:function(){return s.PDFDateString}});Object.defineProperty(t,"PDFWorker",{enumerable:!0,get:function(){return i.PDFWorker}});Object.defineProperty(t,"PasswordResponses",{enumerable:!0,get:function(){return e.PasswordResponses}});Object.defineProperty(t,"PermissionFlag",{enumerable:!0,get:function(){return e.PermissionFlag}});Object.defineProperty(t,"PixelsPerInch",{enumerable:!0,get:function(){return s.PixelsPerInch}});Object.defineProperty(t,"PromiseCapability",{enumerable:!0,get:function(){return e.PromiseCapability}});Object.defineProperty(t,"RenderingCancelledException",{enumerable:!0,get:function(){return s.RenderingCancelledException}});Object.defineProperty(t,"SVGGraphics",{enumerable:!0,get:function(){return i.SVGGraphics}});Object.defineProperty(t,"UnexpectedResponseException",{enumerable:!0,get:function(){return e.UnexpectedResponseException}});Object.defineProperty(t,"Util",{enumerable:!0,get:function(){return e.Util}});Object.defineProperty(t,"VerbosityLevel",{enumerable:!0,get:function(){return e.VerbosityLevel}});Object.defineProperty(t,"XfaLayer",{enumerable:!0,get:function(){return h.XfaLayer}});Object.defineProperty(t,"build",{enumerable:!0,get:function(){return i.build}});Object.defineProperty(t,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return e.createValidAbsoluteUrl}});Object.defineProperty(t,"getDocument",{enumerable:!0,get:function(){return i.getDocument}});Object.defineProperty(t,"getFilenameFromUrl",{enumerable:!0,get:function(){return s.getFilenameFromUrl}});Object.defineProperty(t,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return s.getPdfFilenameFromUrl}});Object.defineProperty(t,"getXfaPageViewport",{enumerable:!0,get:function(){return s.getXfaPageViewport}});Object.defineProperty(t,"isDataScheme",{enumerable:!0,get:function(){return s.isDataScheme}});Object.defineProperty(t,"isPdfFile",{enumerable:!0,get:function(){return s.isPdfFile}});Object.defineProperty(t,"loadScript",{enumerable:!0,get:function(){return s.loadScript}});Object.defineProperty(t,"noContextMenu",{enumerable:!0,get:function(){return s.noContextMenu}});Object.defineProperty(t,"normalizeUnicode",{enumerable:!0,get:function(){return e.normalizeUnicode}});Object.defineProperty(t,"renderTextLayer",{enumerable:!0,get:function(){return n.renderTextLayer}});Object.defineProperty(t,"setLayerDimensions",{enumerable:!0,get:function(){return s.setLayerDimensions}});Object.defineProperty(t,"shadow",{enumerable:!0,get:function(){return e.shadow}});Object.defineProperty(t,"updateTextLayer",{enumerable:!0,get:function(){return n.updateTextLayer}});Object.defineProperty(t,"version",{enumerable:!0,get:function(){return i.version}});var e=__w_pdfjs_require__(1),i=__w_pdfjs_require__(2),s=__w_pdfjs_require__(6),n=__w_pdfjs_require__(26),a=__w_pdfjs_require__(27),r=__w_pdfjs_require__(5),o=__w_pdfjs_require__(29),l=__w_pdfjs_require__(14),h=__w_pdfjs_require__(32)})();return __webpack_exports__})()));
\ No newline at end of file
diff --git a/frontend/public/thumbnailWorker.js b/frontend/public/thumbnailWorker.js
new file mode 100644
index 000000000..2654ce6a4
--- /dev/null
+++ b/frontend/public/thumbnailWorker.js
@@ -0,0 +1,157 @@
+// Web Worker for parallel thumbnail generation
+console.log('🔧 Thumbnail worker starting up...');
+
+let pdfJsLoaded = false;
+
+// Import PDF.js properly for worker context
+try {
+ console.log('📦 Loading PDF.js locally...');
+ importScripts('/pdf.js');
+
+ // PDF.js exports to globalThis, check both self and globalThis
+ const pdfjsLib = self.pdfjsLib || globalThis.pdfjsLib;
+
+ if (pdfjsLib) {
+ // Make it available on self for consistency
+ self.pdfjsLib = pdfjsLib;
+
+ // Set up PDF.js worker
+ self.pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
+ pdfJsLoaded = true;
+ console.log('✓ PDF.js loaded successfully from local files');
+ console.log('✓ PDF.js version:', self.pdfjsLib.version || 'unknown');
+ } else {
+ throw new Error('pdfjsLib not available after import - neither self.pdfjsLib nor globalThis.pdfjsLib found');
+ }
+} catch (error) {
+ console.error('✗ Failed to load local PDF.js:', error.message || error);
+ console.error('✗ Available globals:', Object.keys(self).filter(key => key.includes('pdf')));
+ pdfJsLoaded = false;
+}
+
+// Log the final status
+if (pdfJsLoaded) {
+ console.log('✅ Thumbnail worker ready for PDF processing');
+} else {
+ console.log('❌ Thumbnail worker failed to initialize - PDF.js not available');
+}
+
+self.onmessage = async function(e) {
+ const { type, data, jobId } = e.data;
+
+ try {
+ // Handle PING for worker health check
+ if (type === 'PING') {
+ console.log('🏓 Worker PING received, checking PDF.js status...');
+
+ // Check if PDF.js is loaded before responding
+ if (pdfJsLoaded && self.pdfjsLib) {
+ console.log('✓ Worker PONG - PDF.js ready');
+ self.postMessage({ type: 'PONG', jobId });
+ } else {
+ console.error('✗ PDF.js not loaded - worker not ready');
+ console.error('✗ pdfJsLoaded:', pdfJsLoaded);
+ console.error('✗ self.pdfjsLib:', !!self.pdfjsLib);
+ self.postMessage({
+ type: 'ERROR',
+ jobId,
+ data: { error: 'PDF.js not loaded in worker' }
+ });
+ }
+ return;
+ }
+
+ if (type === 'GENERATE_THUMBNAILS') {
+ console.log('🖼️ Starting thumbnail generation for', data.pageNumbers.length, 'pages');
+
+ if (!pdfJsLoaded || !self.pdfjsLib) {
+ const error = 'PDF.js not available in worker';
+ console.error('✗', error);
+ throw new Error(error);
+ }
+ const { pdfArrayBuffer, pageNumbers, scale = 0.2, quality = 0.8 } = data;
+
+ console.log('📄 Loading PDF document, size:', pdfArrayBuffer.byteLength, 'bytes');
+ // Load PDF in worker using imported PDF.js
+ const pdf = await self.pdfjsLib.getDocument({ data: pdfArrayBuffer }).promise;
+ console.log('✓ PDF loaded, total pages:', pdf.numPages);
+
+ const thumbnails = [];
+
+ // Process pages in smaller batches for smoother UI
+ const batchSize = 3; // Process 3 pages at once for smoother UI
+ for (let i = 0; i < pageNumbers.length; i += batchSize) {
+ const batch = pageNumbers.slice(i, i + batchSize);
+
+ const batchPromises = batch.map(async (pageNumber) => {
+ try {
+ console.log(`🎯 Processing page ${pageNumber}...`);
+ const page = await pdf.getPage(pageNumber);
+ const viewport = page.getViewport({ scale });
+ console.log(`📐 Page ${pageNumber} viewport:`, viewport.width, 'x', viewport.height);
+
+ // Create OffscreenCanvas for better performance
+ const canvas = new OffscreenCanvas(viewport.width, viewport.height);
+ const context = canvas.getContext('2d');
+
+ if (!context) {
+ throw new Error('Failed to get 2D context from OffscreenCanvas');
+ }
+
+ await page.render({ canvasContext: context, viewport }).promise;
+ console.log(`✓ Page ${pageNumber} rendered`);
+
+ // Convert to blob then to base64 (more efficient than toDataURL)
+ const blob = await canvas.convertToBlob({ type: 'image/jpeg', quality });
+ const arrayBuffer = await blob.arrayBuffer();
+ const base64 = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
+ const thumbnail = `data:image/jpeg;base64,${base64}`;
+ console.log(`✓ Page ${pageNumber} thumbnail generated (${base64.length} chars)`);
+
+ return { pageNumber, thumbnail, success: true };
+ } catch (error) {
+ console.error(`✗ Failed to generate thumbnail for page ${pageNumber}:`, error.message || error);
+ return { pageNumber, error: error.message || String(error), success: false };
+ }
+ });
+
+ const batchResults = await Promise.all(batchPromises);
+ thumbnails.push(...batchResults);
+
+ // Send progress update
+ console.log(`📊 Worker: Sending progress update - ${thumbnails.length}/${pageNumbers.length} completed, ${batchResults.filter(r => r.success).length} new thumbnails`);
+ self.postMessage({
+ type: 'PROGRESS',
+ jobId,
+ data: {
+ completed: thumbnails.length,
+ total: pageNumbers.length,
+ thumbnails: batchResults.filter(r => r.success)
+ }
+ });
+
+ // Small delay between batches to keep UI smooth
+ if (i + batchSize < pageNumbers.length) {
+ console.log(`⏸️ Worker: Pausing 100ms before next batch (${i + batchSize}/${pageNumbers.length})`);
+ await new Promise(resolve => setTimeout(resolve, 100)); // Increased to 100ms pause between batches for smoother scrolling
+ }
+ }
+
+ // Clean up
+ pdf.destroy();
+
+ self.postMessage({
+ type: 'COMPLETE',
+ jobId,
+ data: { thumbnails: thumbnails.filter(r => r.success) }
+ });
+
+ }
+ } catch (error) {
+ self.postMessage({
+ type: 'ERROR',
+ jobId,
+ data: { error: error.message }
+ });
+ }
+};
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 8083f37fd..de5001850 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,5 +1,6 @@
import React from 'react';
import { RainbowThemeProvider } from './components/shared/RainbowThemeProvider';
+import { FileContextProvider } from './contexts/FileContext';
import HomePage from './pages/HomePage';
// Import global styles
@@ -9,7 +10,9 @@ import './index.css';
export default function App() {
return (