@embedpdf/engines 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/{browser-C6QEa8uk.cjs → browser-13mzox-R.cjs} +2 -2
  2. package/dist/{browser-C6QEa8uk.cjs.map → browser-13mzox-R.cjs.map} +1 -1
  3. package/dist/{browser-awZxztMA.js → browser-qfUHZxQ6.js} +7 -3
  4. package/dist/{browser-awZxztMA.js.map → browser-qfUHZxQ6.js.map} +1 -1
  5. package/dist/{direct-engine-nrX_KvVy.js → direct-engine-5RWKENek.js} +311 -4
  6. package/dist/direct-engine-5RWKENek.js.map +1 -0
  7. package/dist/direct-engine-DnHo6z8a.cjs +2 -0
  8. package/dist/direct-engine-DnHo6z8a.cjs.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.js +12 -3
  12. package/dist/index.js.map +1 -1
  13. package/dist/lib/converters/browser.d.ts +2 -2
  14. package/dist/lib/converters/index.cjs +1 -1
  15. package/dist/lib/converters/index.js +1 -1
  16. package/dist/lib/converters/types.d.ts +12 -2
  17. package/dist/lib/orchestrator/pdf-engine.d.ts +3 -0
  18. package/dist/lib/orchestrator/remote-executor.d.ts +3 -0
  19. package/dist/lib/pdfium/engine.d.ts +91 -0
  20. package/dist/lib/pdfium/index.cjs +1 -1
  21. package/dist/lib/pdfium/index.js +4 -4
  22. package/dist/lib/pdfium/web/direct-engine.cjs +1 -1
  23. package/dist/lib/pdfium/web/direct-engine.js +3 -3
  24. package/dist/lib/pdfium/web/worker-engine.cjs +1 -1
  25. package/dist/lib/pdfium/web/worker-engine.cjs.map +1 -1
  26. package/dist/lib/pdfium/web/worker-engine.js +12 -3
  27. package/dist/lib/pdfium/web/worker-engine.js.map +1 -1
  28. package/dist/lib/webworker/engine.cjs +1 -1
  29. package/dist/lib/webworker/engine.cjs.map +1 -1
  30. package/dist/lib/webworker/engine.d.ts +18 -0
  31. package/dist/lib/webworker/engine.js +47 -0
  32. package/dist/lib/webworker/engine.js.map +1 -1
  33. package/dist/pdf-engine-B4lt8-5f.cjs +2 -0
  34. package/dist/pdf-engine-B4lt8-5f.cjs.map +1 -0
  35. package/dist/{pdf-engine-ChjNHvQd.js → pdf-engine-CVXuu1xQ.js} +30 -1
  36. package/dist/pdf-engine-CVXuu1xQ.js.map +1 -0
  37. package/dist/preact/index.cjs +1 -1
  38. package/dist/preact/index.js +1 -1
  39. package/dist/react/index.cjs +1 -1
  40. package/dist/react/index.js +1 -1
  41. package/dist/svelte/index.cjs +1 -1
  42. package/dist/svelte/index.js +1 -1
  43. package/dist/vue/index.cjs +1 -1
  44. package/dist/vue/index.js +1 -1
  45. package/package.json +5 -5
  46. package/dist/direct-engine-Dwkk7o9U.cjs +0 -2
  47. package/dist/direct-engine-Dwkk7o9U.cjs.map +0 -1
  48. package/dist/direct-engine-nrX_KvVy.js.map +0 -1
  49. package/dist/pdf-engine-ChjNHvQd.js.map +0 -1
  50. package/dist/pdf-engine-DgNNP62W.cjs +0 -2
  51. package/dist/pdf-engine-DgNNP62W.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdf-engine-CVXuu1xQ.js","sources":["../src/lib/orchestrator/task-queue.ts","../src/lib/orchestrator/pdf-engine.ts"],"sourcesContent":["import { Task, TaskError, Logger, NoopLogger } from '@embedpdf/models';\n\nconst LOG_SOURCE = 'TaskQueue';\nconst LOG_CATEGORY = 'Queue';\n\nexport enum Priority {\n CRITICAL = 3,\n HIGH = 2,\n MEDIUM = 1,\n LOW = 0,\n}\n\n// ============================================================================\n// Type Utilities\n// ============================================================================\n\n/**\n * Extract result type from Task\n */\nexport type ExtractTaskResult<T> = T extends Task<infer R, any, any> ? R : never;\n\n/**\n * Extract error type from Task\n */\nexport type ExtractTaskError<T> = T extends Task<any, infer D, any> ? D : never;\n\n/**\n * Extract progress type from Task\n */\nexport type ExtractTaskProgress<T> = T extends Task<any, any, infer P> ? P : never;\n\n// ============================================================================\n// Queue Interfaces\n// ============================================================================\n\nexport interface QueuedTask<T extends Task<any, any, any>> {\n id: string;\n priority: Priority;\n meta?: Record<string, unknown>;\n executeFactory: () => T; // Factory function - called when it's time to execute!\n cancelled?: boolean;\n}\n\nexport interface EnqueueOptions {\n priority?: Priority;\n meta?: Record<string, unknown>;\n fifo?: boolean;\n}\n\nexport type TaskComparator = (a: QueuedTask<any>, b: QueuedTask<any>) => number;\nexport type TaskRanker = (task: QueuedTask<any>) => number;\n\nexport interface WorkerTaskQueueOptions {\n concurrency?: number;\n comparator?: TaskComparator;\n ranker?: TaskRanker;\n onIdle?: () => void;\n maxQueueSize?: number;\n autoStart?: boolean;\n logger?: Logger;\n}\n\n// ============================================================================\n// WorkerTaskQueue - Corrected with Deferred Execution\n// ============================================================================\n\nexport class WorkerTaskQueue {\n private queue: QueuedTask<any>[] = [];\n private running = 0;\n private resultTasks = new Map<string, Task<any, any, any>>();\n private logger: Logger;\n private opts: Required<Omit<WorkerTaskQueueOptions, 'comparator' | 'ranker' | 'logger'>> & {\n comparator?: TaskComparator;\n ranker?: TaskRanker;\n };\n\n constructor(options: WorkerTaskQueueOptions = {}) {\n const {\n concurrency = 1,\n comparator,\n ranker,\n onIdle,\n maxQueueSize,\n autoStart = true,\n logger,\n } = options;\n this.logger = logger ?? new NoopLogger();\n this.opts = {\n concurrency: Math.max(1, concurrency),\n comparator,\n ranker,\n onIdle: onIdle ?? (() => {}),\n maxQueueSize: maxQueueSize ?? Number.POSITIVE_INFINITY,\n autoStart,\n };\n }\n\n setComparator(comparator?: TaskComparator): void {\n this.opts.comparator = comparator;\n }\n\n setRanker(ranker?: TaskRanker): void {\n this.opts.ranker = ranker;\n }\n\n size(): number {\n return this.queue.length;\n }\n\n inFlight(): number {\n return this.running;\n }\n\n isIdle(): boolean {\n return this.queue.length === 0 && this.running === 0;\n }\n\n async drain(): Promise<void> {\n if (this.isIdle()) return;\n await new Promise<void>((resolve) => {\n const check = () => {\n if (this.isIdle()) {\n this.offIdle(check);\n resolve();\n }\n };\n this.onIdle(check);\n });\n }\n\n private idleListeners = new Set<() => void>();\n private notifyIdle() {\n if (this.isIdle()) {\n [...this.idleListeners].forEach((fn) => fn());\n this.idleListeners.clear();\n this.opts.onIdle();\n }\n }\n private onIdle(fn: () => void) {\n this.idleListeners.add(fn);\n }\n private offIdle(fn: () => void) {\n this.idleListeners.delete(fn);\n }\n\n /**\n * Enqueue a task factory - with automatic type inference!\n *\n * The factory function is ONLY called when it's the task's turn to execute.\n *\n * Usage:\n * const task = queue.enqueue({\n * execute: () => this.executor.getMetadata(doc), // Factory - not called yet!\n * meta: { operation: 'getMetadata' }\n * }, { priority: Priority.LOW });\n *\n * The returned task has the SAME type as executor.getMetadata() would return!\n */\n enqueue<T extends Task<any, any, any>>(\n taskDef: {\n execute: () => T; // Factory function that returns Task when called!\n meta?: Record<string, unknown>;\n },\n options: EnqueueOptions = {},\n ): T {\n const id = this.generateId();\n const priority = options.priority ?? Priority.MEDIUM;\n\n // Create a proxy task that we return to the user\n // This task bridges to the real task that will be created later\n const resultTask = new Task<\n ExtractTaskResult<T>,\n ExtractTaskError<T>,\n ExtractTaskProgress<T>\n >() as T;\n\n if (this.queue.length >= this.opts.maxQueueSize) {\n const error = new Error('Queue is full (maxQueueSize reached).');\n resultTask.reject(error as any);\n return resultTask;\n }\n\n // Store the result task for bridging\n this.resultTasks.set(id, resultTask);\n\n const queuedTask: QueuedTask<T> = {\n id,\n priority,\n meta: options.meta ?? taskDef.meta,\n executeFactory: taskDef.execute, // Store factory, don't call it yet!\n };\n\n this.queue.push(queuedTask);\n\n this.logger.debug(\n LOG_SOURCE,\n LOG_CATEGORY,\n `Task enqueued: ${id} | Priority: ${priority} | Running: ${this.running} | Queued: ${this.queue.length}`,\n );\n\n // Set up automatic abort handling\n // When result task is aborted externally, remove from queue\n const originalAbort = resultTask.abort.bind(resultTask);\n resultTask.abort = (reason: any) => {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Task aborted: ${id}`);\n this.cancel(id);\n originalAbort(reason);\n };\n\n if (this.opts.autoStart) this.process(options.fifo === true);\n\n return resultTask;\n }\n\n /**\n * Cancel/remove a task from the queue\n */\n private cancel(taskId: string): void {\n const before = this.queue.length;\n this.queue = this.queue.filter((t) => {\n if (t.id === taskId) {\n t.cancelled = true;\n return false;\n }\n return true;\n });\n\n this.resultTasks.delete(taskId);\n\n if (before !== this.queue.length) {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Task cancelled and removed: ${taskId}`);\n this.kick();\n }\n }\n\n private kick() {\n queueMicrotask(() => this.process());\n }\n\n private async process(fifo = false): Promise<void> {\n this.logger.debug(\n LOG_SOURCE,\n LOG_CATEGORY,\n `process() called | Running: ${this.running} | Concurrency: ${this.opts.concurrency} | Queued: ${this.queue.length}`,\n );\n\n while (this.running < this.opts.concurrency && this.queue.length > 0) {\n this.logger.debug(\n LOG_SOURCE,\n LOG_CATEGORY,\n `Starting new task | Running: ${this.running} | Queued: ${this.queue.length}`,\n );\n\n if (!fifo) this.sortQueue();\n\n const queuedTask = this.queue.shift()!;\n if (queuedTask.cancelled) {\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, `Skipping cancelled task: ${queuedTask.id}`);\n continue;\n }\n\n const resultTask = this.resultTasks.get(queuedTask.id);\n if (!resultTask) continue; // Shouldn't happen, but guard anyway.\n\n this.running++;\n\n // NOW call the factory to create the real task!\n (async () => {\n let realTask: Task<any, any, any> | null = null;\n\n try {\n // Call the factory function NOW - this is when execution actually starts\n realTask = queuedTask.executeFactory();\n\n // Guard against null/undefined return from factory\n if (!realTask) {\n throw new Error('Task factory returned null/undefined');\n }\n\n // Bridge the real task to the result task\n realTask.wait(\n (result) => {\n if (resultTask.state.stage === 0 /* Pending */) {\n resultTask.resolve(result);\n }\n },\n (error) => {\n if (resultTask.state.stage === 0 /* Pending */) {\n if (error.type === 'abort') {\n resultTask.abort(error.reason);\n } else {\n resultTask.reject(error.reason);\n }\n }\n },\n );\n\n // Bridge progress\n realTask.onProgress((progress) => {\n resultTask.progress(progress);\n });\n\n // Wait for completion\n await realTask.toPromise();\n } catch (error) {\n // Handle any errors from factory or execution\n if (resultTask.state.stage === 0 /* Pending */) {\n resultTask.reject(error as any);\n }\n } finally {\n this.resultTasks.delete(queuedTask.id);\n this.running--;\n\n this.logger.debug(\n LOG_SOURCE,\n LOG_CATEGORY,\n `Task completed: ${queuedTask.id} | Running: ${this.running} | Queued: ${this.queue.length}`,\n );\n\n if (this.isIdle()) {\n this.notifyIdle();\n } else if (this.queue.length > 0) {\n this.kick();\n }\n }\n })().catch((error) => {\n this.logger.error(\n LOG_SOURCE,\n LOG_CATEGORY,\n 'Unhandled error in task execution wrapper:',\n error,\n );\n this.running = Math.max(0, this.running - 1);\n if (this.isIdle()) {\n this.notifyIdle();\n } else if (this.queue.length > 0) {\n this.kick();\n }\n });\n }\n }\n\n private sortQueue(): void {\n const { comparator, ranker } = this.opts;\n if (comparator) {\n this.queue.sort(comparator);\n return;\n }\n\n const rankCache = new Map<string, number>();\n const getRank = (t: QueuedTask<any>) => {\n if (!ranker) return this.defaultRank(t);\n if (!rankCache.has(t.id)) rankCache.set(t.id, ranker(t));\n return rankCache.get(t.id)!;\n };\n\n this.queue.sort((a, b) => {\n if (a.priority !== b.priority) return b.priority - a.priority;\n const ar = getRank(a);\n const br = getRank(b);\n if (ar !== br) return br - ar;\n return this.extractTime(a.id) - this.extractTime(b.id);\n });\n }\n\n private defaultRank(_task: QueuedTask<any>): number {\n return 0;\n }\n\n private generateId(): string {\n if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n }\n\n private extractTime(id: string): number {\n const t = Number(id.split('-')[0]);\n return Number.isFinite(t) ? t : 0;\n }\n}\n","import {\n BatchProgress,\n Logger,\n NoopLogger,\n PdfEngine as IPdfEngine,\n PdfDocumentObject,\n PdfPageObject,\n PdfTask,\n PdfErrorReason,\n PdfFileUrl,\n PdfFile,\n PdfOpenDocumentUrlOptions,\n PdfOpenDocumentBufferOptions,\n PdfMetadataObject,\n PdfBookmarksObject,\n PdfBookmarkObject,\n PdfRenderPageOptions,\n PdfRenderThumbnailOptions,\n PdfRenderPageAnnotationOptions,\n PdfAnnotationObject,\n PdfTextRectObject,\n PdfSearchAllPagesOptions,\n SearchAllPagesResult,\n PdfPageSearchProgress,\n PdfAnnotationsProgress,\n PdfAttachmentObject,\n PdfAddAttachmentParams,\n PdfWidgetAnnoObject,\n FormFieldValue,\n PdfFlattenPageOptions,\n PdfPageFlattenResult,\n PdfRedactTextOptions,\n Rect,\n PageTextSlice,\n PdfGlyphObject,\n PdfPageGeometry,\n PdfPrintOptions,\n PdfEngineFeature,\n PdfEngineOperation,\n PdfSignatureObject,\n AnnotationCreateContext,\n Task,\n PdfErrorCode,\n SearchResult,\n CompoundTask,\n ImageDataLike,\n IPdfiumExecutor,\n} from '@embedpdf/models';\nimport { WorkerTaskQueue, Priority } from './task-queue';\nimport type { ImageDataConverter } from '../converters/types';\n\n// Re-export for convenience\nexport type { ImageDataConverter } from '../converters/types';\nexport type { ImageDataLike, IPdfiumExecutor, BatchProgress } from '@embedpdf/models';\n\nconst LOG_SOURCE = 'PdfEngine';\nconst LOG_CATEGORY = 'Orchestrator';\n\nexport interface PdfEngineOptions<T> {\n /**\n * Image data converter (for encoding raw image data to Blob/other format)\n */\n imageConverter: ImageDataConverter<T>;\n /**\n * Fetch function for fetching remote URLs\n */\n fetcher?: typeof fetch;\n /**\n * Logger instance\n */\n logger?: Logger;\n}\n\n/**\n * PdfEngine orchestrator\n *\n * This is the \"smart\" layer that:\n * - Implements the PdfEngine interface\n * - Uses WorkerTaskQueue for priority-based task scheduling\n * - Orchestrates complex multi-page operations\n * - Handles image encoding with separate encoder pool\n * - Manages visibility-based task ranking\n */\nexport class PdfEngine<T = Blob> implements IPdfEngine<T> {\n private executor: IPdfiumExecutor;\n private workerQueue: WorkerTaskQueue;\n private logger: Logger;\n private options: PdfEngineOptions<T>;\n\n constructor(executor: IPdfiumExecutor, options: PdfEngineOptions<T>) {\n this.executor = executor;\n this.logger = options.logger ?? new NoopLogger();\n this.options = {\n imageConverter: options.imageConverter,\n fetcher:\n options.fetcher ??\n (typeof fetch !== 'undefined' ? (url, init) => fetch(url, init) : undefined),\n logger: this.logger,\n };\n\n // Create worker queue with single concurrency (PDFium is single-threaded)\n this.workerQueue = new WorkerTaskQueue({\n concurrency: 1,\n autoStart: true,\n logger: this.logger,\n });\n\n this.logger.debug(LOG_SOURCE, LOG_CATEGORY, 'PdfEngine orchestrator created');\n }\n\n /**\n * Split an array into chunks of a given size\n */\n private chunkArray<U>(items: U[], chunkSize: number): U[][] {\n const chunks: U[][] = [];\n for (let i = 0; i < items.length; i += chunkSize) {\n chunks.push(items.slice(i, i + chunkSize));\n }\n return chunks;\n }\n\n // ========== IPdfEngine Implementation ==========\n\n isSupport(feature: PdfEngineFeature): PdfTask<PdfEngineOperation[]> {\n const task = new Task<PdfEngineOperation[], PdfErrorReason>();\n // PDFium supports all features\n task.resolve([\n PdfEngineOperation.Create,\n PdfEngineOperation.Read,\n PdfEngineOperation.Update,\n PdfEngineOperation.Delete,\n ]);\n return task;\n }\n\n destroy(): PdfTask<boolean> {\n const task = new Task<boolean, PdfErrorReason>();\n try {\n this.executor.destroy();\n // Clean up image converter resources (e.g., encoder worker pool)\n this.options.imageConverter.destroy?.();\n task.resolve(true);\n } catch (error) {\n task.reject({ code: PdfErrorCode.Unknown, message: String(error) });\n }\n return task;\n }\n\n openDocumentUrl(\n file: PdfFileUrl,\n options?: PdfOpenDocumentUrlOptions,\n ): PdfTask<PdfDocumentObject> {\n const task = new Task<PdfDocumentObject, PdfErrorReason>();\n\n // Handle fetch in main thread (not worker!)\n (async () => {\n try {\n if (!this.options.fetcher) {\n throw new Error('Fetcher is not set');\n }\n\n const response = await this.options.fetcher(file.url, options?.requestOptions);\n const arrayBuf = await response.arrayBuffer();\n\n const pdfFile: PdfFile = {\n id: file.id,\n content: arrayBuf,\n };\n\n // Then open in worker - use wait() to properly propagate task errors\n this.openDocumentBuffer(pdfFile, {\n password: options?.password,\n }).wait(\n (doc) => task.resolve(doc),\n (error) => task.fail(error),\n );\n } catch (error) {\n // This only catches fetch errors (network issues, etc.)\n task.reject({ code: PdfErrorCode.Unknown, message: String(error) });\n }\n })();\n\n return task;\n }\n\n openDocumentBuffer(\n file: PdfFile,\n options?: PdfOpenDocumentBufferOptions,\n ): PdfTask<PdfDocumentObject> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.openDocumentBuffer(file, options),\n meta: { docId: file.id, operation: 'openDocumentBuffer' },\n },\n { priority: Priority.CRITICAL },\n );\n }\n\n getMetadata(doc: PdfDocumentObject): PdfTask<PdfMetadataObject> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getMetadata(doc),\n meta: { docId: doc.id, operation: 'getMetadata' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n setMetadata(doc: PdfDocumentObject, metadata: Partial<PdfMetadataObject>): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.setMetadata(doc, metadata),\n meta: { docId: doc.id, operation: 'setMetadata' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getDocPermissions(doc: PdfDocumentObject): PdfTask<number> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getDocPermissions(doc),\n meta: { docId: doc.id, operation: 'getDocPermissions' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getDocUserPermissions(doc: PdfDocumentObject): PdfTask<number> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getDocUserPermissions(doc),\n meta: { docId: doc.id, operation: 'getDocUserPermissions' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getSignatures(doc: PdfDocumentObject): PdfTask<PdfSignatureObject[]> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getSignatures(doc),\n meta: { docId: doc.id, operation: 'getSignatures' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getBookmarks(doc: PdfDocumentObject): PdfTask<PdfBookmarksObject> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getBookmarks(doc),\n meta: { docId: doc.id, operation: 'getBookmarks' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n setBookmarks(doc: PdfDocumentObject, bookmarks: PdfBookmarkObject[]): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.setBookmarks(doc, bookmarks),\n meta: { docId: doc.id, operation: 'setBookmarks' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n deleteBookmarks(doc: PdfDocumentObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.deleteBookmarks(doc),\n meta: { docId: doc.id, operation: 'deleteBookmarks' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n // ========== Rendering with Encoding ==========\n\n renderPage(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n options?: PdfRenderPageOptions,\n ): PdfTask<T> {\n return this.renderWithEncoding(\n () => this.executor.renderPageRaw(doc, page, options),\n options,\n doc.id,\n page.index,\n Priority.CRITICAL,\n );\n }\n\n renderPageRect(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n rect: Rect,\n options?: PdfRenderPageOptions,\n ): PdfTask<T> {\n return this.renderWithEncoding(\n () => this.executor.renderPageRect(doc, page, rect, options),\n options,\n doc.id,\n page.index,\n Priority.HIGH,\n );\n }\n\n renderThumbnail(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n options?: PdfRenderThumbnailOptions,\n ): PdfTask<T> {\n return this.renderWithEncoding(\n () => this.executor.renderThumbnailRaw(doc, page, options),\n options,\n doc.id,\n page.index,\n Priority.MEDIUM,\n );\n }\n\n renderPageAnnotation(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: PdfAnnotationObject,\n options?: PdfRenderPageAnnotationOptions,\n ): PdfTask<T> {\n return this.renderWithEncoding(\n () => this.executor.renderPageAnnotationRaw(doc, page, annotation, options),\n options,\n doc.id,\n page.index,\n Priority.MEDIUM,\n );\n }\n\n /**\n * Helper to render and encode in two stages with priority queue\n */\n private renderWithEncoding(\n renderFn: () => PdfTask<ImageDataLike>,\n options?: PdfRenderPageOptions | PdfRenderThumbnailOptions | PdfRenderPageAnnotationOptions,\n docId?: string,\n pageIndex?: number,\n priority: Priority = Priority.CRITICAL,\n ): PdfTask<T> {\n const resultTask = new Task<T, PdfErrorReason>();\n\n // Step 1: Add HIGH/MEDIUM priority task to render raw bytes\n const renderHandle = this.workerQueue.enqueue(\n {\n execute: () => renderFn(),\n meta: { docId, pageIndex, operation: 'render' },\n },\n { priority },\n );\n\n // Wire up abort: when resultTask is aborted, also abort the queue task\n const originalAbort = resultTask.abort.bind(resultTask);\n resultTask.abort = (reason) => {\n renderHandle.abort(reason); // Cancel the queue task!\n originalAbort(reason);\n };\n\n renderHandle.wait(\n (rawImageData) => {\n // Check if resultTask was already aborted before encoding\n if (resultTask.state.stage !== 0 /* Pending */) {\n return;\n }\n this.encodeImage(rawImageData, options, resultTask);\n },\n (error) => {\n // Only forward error if resultTask is still pending\n if (resultTask.state.stage === 0 /* Pending */) {\n resultTask.fail(error);\n }\n },\n );\n\n return resultTask;\n }\n\n /**\n * Encode image using encoder pool or inline\n */\n private encodeImage(\n rawImageData: ImageDataLike,\n options: any,\n resultTask: Task<T, PdfErrorReason>,\n ): void {\n const imageType = options?.imageType ?? 'image/webp';\n const quality = options?.quality;\n\n // Convert to plain object for encoding\n const plainImageData = {\n data: new Uint8ClampedArray(rawImageData.data),\n width: rawImageData.width,\n height: rawImageData.height,\n };\n\n this.options\n .imageConverter(() => plainImageData, imageType, quality)\n .then((result) => resultTask.resolve(result))\n .catch((error) => resultTask.reject({ code: PdfErrorCode.Unknown, message: String(error) }));\n }\n\n // ========== Annotations ==========\n\n getPageAnnotations(doc: PdfDocumentObject, page: PdfPageObject): PdfTask<PdfAnnotationObject[]> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getPageAnnotations(doc, page),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'getPageAnnotations' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n createPageAnnotation<A extends PdfAnnotationObject>(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: A,\n context?: AnnotationCreateContext<A>,\n ): PdfTask<string> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.createPageAnnotation(doc, page, annotation, context),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'createPageAnnotation' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n updatePageAnnotation(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: PdfAnnotationObject,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.updatePageAnnotation(doc, page, annotation),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'updatePageAnnotation' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n removePageAnnotation(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: PdfAnnotationObject,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.removePageAnnotation(doc, page, annotation),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'removePageAnnotation' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n /**\n * Get all annotations across all pages\n * Uses batched operations to reduce queue overhead\n */\n getAllAnnotations(\n doc: PdfDocumentObject,\n ): CompoundTask<Record<number, PdfAnnotationObject[]>, PdfErrorReason, PdfAnnotationsProgress> {\n // Chunk pages for batched processing\n const chunks = this.chunkArray(doc.pages, 500);\n\n this.logger.debug(\n LOG_SOURCE,\n LOG_CATEGORY,\n `getAllAnnotations: ${doc.pages.length} pages in ${chunks.length} chunks`,\n );\n\n // Create compound task for result aggregation\n const compound = new CompoundTask<\n Record<number, PdfAnnotationObject[]>,\n PdfErrorReason,\n PdfAnnotationsProgress\n >({\n aggregate: (results) => Object.assign({}, ...results),\n });\n\n // Create one task per chunk and wire up progress forwarding\n chunks.forEach((chunkPages, chunkIndex) => {\n const batchTask = this.workerQueue.enqueue(\n {\n execute: () => this.executor.getAnnotationsBatch(doc, chunkPages),\n meta: { docId: doc.id, operation: 'getAnnotationsBatch', chunkSize: chunkPages.length },\n },\n { priority: Priority.LOW },\n );\n\n // Forward batch progress (per-page) to compound task\n batchTask.onProgress((batchProgress: BatchProgress<PdfAnnotationObject[]>) => {\n compound.progress({\n page: batchProgress.pageIndex,\n result: batchProgress.result,\n });\n });\n\n compound.addChild(batchTask, chunkIndex);\n });\n\n compound.finalize();\n return compound;\n }\n\n getPageTextRects(doc: PdfDocumentObject, page: PdfPageObject): PdfTask<PdfTextRectObject[]> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getPageTextRects(doc, page),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'getPageTextRects' },\n },\n {\n priority: Priority.MEDIUM,\n },\n );\n }\n\n // ========== Search ==========\n\n /**\n * Search across all pages\n * Uses batched operations to reduce queue overhead\n */\n searchAllPages(\n doc: PdfDocumentObject,\n keyword: string,\n options?: PdfSearchAllPagesOptions,\n ): PdfTask<SearchAllPagesResult, PdfPageSearchProgress> {\n const flags = Array.isArray(options?.flags)\n ? options.flags.reduce((acc, flag) => acc | flag, 0)\n : (options?.flags ?? 0);\n\n // Chunk pages for batched processing\n const chunks = this.chunkArray(doc.pages, 25);\n\n this.logger.debug(\n LOG_SOURCE,\n LOG_CATEGORY,\n `searchAllPages: ${doc.pages.length} pages in ${chunks.length} chunks`,\n );\n\n // Create compound task for result aggregation\n const compound = new CompoundTask<SearchAllPagesResult, PdfErrorReason, PdfPageSearchProgress>({\n aggregate: (results) => {\n // Merge all batch results into a flat array\n const allResults = results.flatMap((batchResult: Record<number, SearchResult[]>) =>\n Object.values(batchResult).flat(),\n );\n return { results: allResults, total: allResults.length };\n },\n });\n\n // Create one task per chunk and wire up progress forwarding\n chunks.forEach((chunkPages, chunkIndex) => {\n const batchTask = this.workerQueue.enqueue(\n {\n execute: () => this.executor.searchBatch(doc, chunkPages, keyword, flags),\n meta: { docId: doc.id, operation: 'searchBatch', chunkSize: chunkPages.length },\n },\n { priority: Priority.LOW },\n );\n\n // Forward batch progress (per-page) to compound task\n batchTask.onProgress((batchProgress: BatchProgress<SearchResult[]>) => {\n compound.progress({\n page: batchProgress.pageIndex,\n results: batchProgress.result,\n });\n });\n\n compound.addChild(batchTask, chunkIndex);\n });\n\n compound.finalize();\n return compound;\n }\n\n // ========== Attachments ==========\n\n getAttachments(doc: PdfDocumentObject): PdfTask<PdfAttachmentObject[]> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getAttachments(doc),\n meta: { docId: doc.id, operation: 'getAttachments' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n addAttachment(doc: PdfDocumentObject, params: PdfAddAttachmentParams): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.addAttachment(doc, params),\n meta: { docId: doc.id, operation: 'addAttachment' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n removeAttachment(doc: PdfDocumentObject, attachment: PdfAttachmentObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.removeAttachment(doc, attachment),\n meta: { docId: doc.id, operation: 'removeAttachment' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n readAttachmentContent(\n doc: PdfDocumentObject,\n attachment: PdfAttachmentObject,\n ): PdfTask<ArrayBuffer> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.readAttachmentContent(doc, attachment),\n meta: { docId: doc.id, operation: 'readAttachmentContent' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n // ========== Forms ==========\n\n setFormFieldValue(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: PdfWidgetAnnoObject,\n value: FormFieldValue,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.setFormFieldValue(doc, page, annotation, value),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'setFormFieldValue' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n flattenPage(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n options?: PdfFlattenPageOptions,\n ): PdfTask<PdfPageFlattenResult> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.flattenPage(doc, page, options),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'flattenPage' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n // ========== Text Operations ==========\n\n extractPages(doc: PdfDocumentObject, pageIndexes: number[]): PdfTask<ArrayBuffer> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.extractPages(doc, pageIndexes),\n meta: { docId: doc.id, pageIndexes: pageIndexes, operation: 'extractPages' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n extractText(doc: PdfDocumentObject, pageIndexes: number[]): PdfTask<string> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.extractText(doc, pageIndexes),\n meta: { docId: doc.id, pageIndexes: pageIndexes, operation: 'extractText' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n redactTextInRects(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n rects: Rect[],\n options?: PdfRedactTextOptions,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.redactTextInRects(doc, page, rects, options),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'redactTextInRects' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n applyRedaction(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: PdfAnnotationObject,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.applyRedaction(doc, page, annotation),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'applyRedaction' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n applyAllRedactions(doc: PdfDocumentObject, page: PdfPageObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.applyAllRedactions(doc, page),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'applyAllRedactions' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n flattenAnnotation(\n doc: PdfDocumentObject,\n page: PdfPageObject,\n annotation: PdfAnnotationObject,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.flattenAnnotation(doc, page, annotation),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'flattenAnnotation' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getTextSlices(doc: PdfDocumentObject, slices: PageTextSlice[]): PdfTask<string[]> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getTextSlices(doc, slices),\n meta: { docId: doc.id, slices: slices, operation: 'getTextSlices' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getPageGlyphs(doc: PdfDocumentObject, page: PdfPageObject): PdfTask<PdfGlyphObject[]> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getPageGlyphs(doc, page),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'getPageGlyphs' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n getPageGeometry(doc: PdfDocumentObject, page: PdfPageObject): PdfTask<PdfPageGeometry> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.getPageGeometry(doc, page),\n meta: { docId: doc.id, pageIndex: page.index, operation: 'getPageGeometry' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n // ========== Document Operations ==========\n\n merge(files: PdfFile[]): PdfTask<PdfFile> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.merge(files),\n meta: { docId: files.map((file) => file.id).join(','), operation: 'merge' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n mergePages(mergeConfigs: Array<{ docId: string; pageIndices: number[] }>): PdfTask<PdfFile> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.mergePages(mergeConfigs),\n meta: {\n docId: mergeConfigs.map((config) => config.docId).join(','),\n operation: 'mergePages',\n },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n preparePrintDocument(doc: PdfDocumentObject, options?: PdfPrintOptions): PdfTask<ArrayBuffer> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.preparePrintDocument(doc, options),\n meta: { docId: doc.id, operation: 'preparePrintDocument' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n saveAsCopy(doc: PdfDocumentObject): PdfTask<ArrayBuffer> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.saveAsCopy(doc),\n meta: { docId: doc.id, operation: 'saveAsCopy' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n closeDocument(doc: PdfDocumentObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.closeDocument(doc),\n meta: { docId: doc.id, operation: 'closeDocument' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n closeAllDocuments(): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.closeAllDocuments(),\n meta: { operation: 'closeAllDocuments' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.setDocumentEncryption}\n */\n setDocumentEncryption(\n doc: PdfDocumentObject,\n userPassword: string,\n ownerPassword: string,\n allowedFlags: number,\n ): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () =>\n this.executor.setDocumentEncryption(doc, userPassword, ownerPassword, allowedFlags),\n meta: { docId: doc.id, operation: 'setDocumentEncryption' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.removeEncryption}\n */\n removeEncryption(doc: PdfDocumentObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.removeEncryption(doc),\n meta: { docId: doc.id, operation: 'removeEncryption' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.unlockOwnerPermissions}\n */\n unlockOwnerPermissions(doc: PdfDocumentObject, ownerPassword: string): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.unlockOwnerPermissions(doc, ownerPassword),\n meta: { docId: doc.id, operation: 'unlockOwnerPermissions' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.isEncrypted}\n */\n isEncrypted(doc: PdfDocumentObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.isEncrypted(doc),\n meta: { docId: doc.id, operation: 'isEncrypted' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n\n /**\n * {@inheritDoc @embedpdf/models!PdfEngine.isOwnerUnlocked}\n */\n isOwnerUnlocked(doc: PdfDocumentObject): PdfTask<boolean> {\n return this.workerQueue.enqueue(\n {\n execute: () => this.executor.isOwnerUnlocked(doc),\n meta: { docId: doc.id, operation: 'isOwnerUnlocked' },\n },\n { priority: Priority.MEDIUM },\n );\n }\n}\n"],"names":["LOG_SOURCE","LOG_CATEGORY","Priority"],"mappings":";AAEA,MAAMA,eAAa;AACnB,MAAMC,iBAAe;AAEd,IAAK,6BAAAC,cAAL;AACLA,YAAAA,UAAA,cAAW,CAAA,IAAX;AACAA,YAAAA,UAAA,UAAO,CAAA,IAAP;AACAA,YAAAA,UAAA,YAAS,CAAA,IAAT;AACAA,YAAAA,UAAA,SAAM,CAAA,IAAN;AAJU,SAAAA;AAAA,GAAA,YAAA,CAAA,CAAA;AA6DL,MAAM,gBAAgB;AAAA,EAU3B,YAAY,UAAkC,IAAI;AATlD,SAAQ,QAA2B,CAAA;AACnC,SAAQ,UAAU;AAClB,SAAQ,kCAAkB,IAAA;AA6D1B,SAAQ,oCAAoB,IAAA;AArD1B,UAAM;AAAA,MACJ,cAAc;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,YAAY;AAAA,MACZ;AAAA,IAAA,IACE;AACJ,SAAK,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EAAE,UAAU,SAAS,OAAA;AAAA,IAAO;AAAA,EAEhC;AAAA;AAAA;AAAA;AAAA,EAKA,uBAAuB,KAAwB,eAAyC;AACtF,WAAO,KAAK,YAAY;AAAA,MACtB;AAAA,QACE,SAAS,MAAM,KAAK,SAAS,uBAAuB,KAAK,aAAa;AAAA,QACtE,MAAM,EAAE,OAAO,IAAI,IAAI,WAAW,yBAAA;AAAA,MAAyB;AAAA,MAE7D,EAAE,UAAU,SAAS,OAAA;AAAA,IAAO;AAAA,EAEhC;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY,KAA0C;AACpD,WAAO,KAAK,YAAY;AAAA,MACtB;AAAA,QACE,SAAS,MAAM,KAAK,SAAS,YAAY,GAAG;AAAA,QAC5C,MAAM,EAAE,OAAO,IAAI,IAAI,WAAW,cAAA;AAAA,MAAc;AAAA,MAElD,EAAE,UAAU,SAAS,OAAA;AAAA,IAAO;AAAA,EAEhC;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB,KAA0C;AACxD,WAAO,KAAK,YAAY;AAAA,MACtB;AAAA,QACE,SAAS,MAAM,KAAK,SAAS,gBAAgB,GAAG;AAAA,QAChD,MAAM,EAAE,OAAO,IAAI,IAAI,WAAW,kBAAA;AAAA,MAAkB;AAAA,MAEtD,EAAE,UAAU,SAAS,OAAA;AAAA,IAAO;AAAA,EAEhC;AACF;"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("preact/hooks"),r=require("preact"),t=require("@embedpdf/models"),n=require("preact/jsx-runtime"),o="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm";const i=r.createContext(void 0);function u(){const r=e.useContext(i);if(void 0===r)throw new Error("useEngineContext must be used within a PdfEngineProvider");return r}exports.PdfEngineProvider=function({children:e,engine:r,isLoading:t,error:o}){const u={engine:r,isLoading:t,error:o};return n.jsx(i.Provider,{value:u,children:e})},exports.useEngine=function(){const{engine:e,error:r}=u();if(r)throw r;return e},exports.useEngineContext=u,exports.usePdfiumEngine=function(r){const{wasmUrl:n=o,worker:i=!0,logger:u,encoderPoolSize:s,fontFallback:c}=r??{},[l,d]=e.useState(null),[a,p]=e.useState(!0),[g,f]=e.useState(null),m=e.useRef(null);return e.useEffect(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=i?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),r=await e(n,{logger:u,encoderPoolSize:s,fontFallback:c});m.current=r,d(r),p(!1)}catch(r){e||(f(r),p(!1))}})(),()=>{var r,n;e=!0,null==(n=null==(r=m.current)?void 0:r.closeAllDocuments)||n.call(r).wait(()=>{var e,r;null==(r=null==(e=m.current)?void 0:e.destroy)||r.call(e),m.current=null},t.ignore)}},[n,i,u,c]),{engine:l,isLoading:a,error:g}};
1
+ "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("preact/hooks"),r=require("preact"),t=require("@embedpdf/models"),n=require("preact/jsx-runtime"),o="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm";const i=r.createContext(void 0);function u(){const r=e.useContext(i);if(void 0===r)throw new Error("useEngineContext must be used within a PdfEngineProvider");return r}exports.PdfEngineProvider=function({children:e,engine:r,isLoading:t,error:o}){const u={engine:r,isLoading:t,error:o};return n.jsx(i.Provider,{value:u,children:e})},exports.useEngine=function(){const{engine:e,error:r}=u();if(r)throw r;return e},exports.useEngineContext=u,exports.usePdfiumEngine=function(r){const{wasmUrl:n=o,worker:i=!0,logger:u,encoderPoolSize:s,fontFallback:c}=r??{},[l,d]=e.useState(null),[a,p]=e.useState(!0),[g,f]=e.useState(null),m=e.useRef(null);return e.useEffect(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=i?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),r=await e(n,{logger:u,encoderPoolSize:s,fontFallback:c});m.current=r,d(r),p(!1)}catch(r){e||(f(r),p(!1))}})(),()=>{var r,n;e=!0,null==(n=null==(r=m.current)?void 0:r.closeAllDocuments)||n.call(r).wait(()=>{var e,r;null==(r=null==(e=m.current)?void 0:e.destroy)||r.call(e),m.current=null},t.ignore)}},[n,i,u,c]),{engine:l,isLoading:a,error:g}};
2
2
  //# sourceMappingURL=index.cjs.map
@@ -2,7 +2,7 @@ import { useState, useRef, useEffect, useContext } from "preact/hooks";
2
2
  import { createContext } from "preact";
3
3
  import { ignore } from "@embedpdf/models";
4
4
  import { jsx } from "preact/jsx-runtime";
5
- const defaultWasmUrl = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm`;
5
+ const defaultWasmUrl = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm`;
6
6
  function usePdfiumEngine(config) {
7
7
  const {
8
8
  wasmUrl = defaultWasmUrl,
@@ -1,2 +1,2 @@
1
- "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),r=require("@embedpdf/models"),t=require("react/jsx-runtime"),n="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm";const o=e.createContext(void 0);function i(){const r=e.useContext(o);if(void 0===r)throw new Error("useEngineContext must be used within a PdfEngineProvider");return r}exports.PdfEngineProvider=function({children:e,engine:r,isLoading:n,error:i}){const u={engine:r,isLoading:n,error:i};return t.jsx(o.Provider,{value:u,children:e})},exports.useEngine=function(){const{engine:e,error:r}=i();if(r)throw r;return e},exports.useEngineContext=i,exports.usePdfiumEngine=function(t){const{wasmUrl:o=n,worker:i=!0,logger:u,encoderPoolSize:s,fontFallback:c}=t??{},[l,d]=e.useState(null),[a,g]=e.useState(!0),[f,p]=e.useState(null),m=e.useRef(null);return e.useEffect(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=i?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),r=await e(o,{logger:u,encoderPoolSize:s,fontFallback:c});m.current=r,d(r),g(!1)}catch(r){e||(p(r),g(!1))}})(),()=>{var t,n;e=!0,null==(n=null==(t=m.current)?void 0:t.closeAllDocuments)||n.call(t).wait(()=>{var e,r;null==(r=null==(e=m.current)?void 0:e.destroy)||r.call(e),m.current=null},r.ignore)}},[o,i,u,c]),{engine:l,isLoading:a,error:f}};
1
+ "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),r=require("@embedpdf/models"),t=require("react/jsx-runtime"),n="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm";const o=e.createContext(void 0);function i(){const r=e.useContext(o);if(void 0===r)throw new Error("useEngineContext must be used within a PdfEngineProvider");return r}exports.PdfEngineProvider=function({children:e,engine:r,isLoading:n,error:i}){const u={engine:r,isLoading:n,error:i};return t.jsx(o.Provider,{value:u,children:e})},exports.useEngine=function(){const{engine:e,error:r}=i();if(r)throw r;return e},exports.useEngineContext=i,exports.usePdfiumEngine=function(t){const{wasmUrl:o=n,worker:i=!0,logger:u,encoderPoolSize:s,fontFallback:c}=t??{},[l,d]=e.useState(null),[a,g]=e.useState(!0),[f,p]=e.useState(null),m=e.useRef(null);return e.useEffect(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=i?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),r=await e(o,{logger:u,encoderPoolSize:s,fontFallback:c});m.current=r,d(r),g(!1)}catch(r){e||(p(r),g(!1))}})(),()=>{var t,n;e=!0,null==(n=null==(t=m.current)?void 0:t.closeAllDocuments)||n.call(t).wait(()=>{var e,r;null==(r=null==(e=m.current)?void 0:e.destroy)||r.call(e),m.current=null},r.ignore)}},[o,i,u,c]),{engine:l,isLoading:a,error:f}};
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  import { useState, useRef, useEffect, createContext, useContext } from "react";
2
2
  import { ignore } from "@embedpdf/models";
3
3
  import { jsx } from "react/jsx-runtime";
4
- const defaultWasmUrl = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm`;
4
+ const defaultWasmUrl = `https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm`;
5
5
  function usePdfiumEngine(config) {
6
6
  const {
7
7
  wasmUrl = defaultWasmUrl,
@@ -1,2 +1,2 @@
1
- "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("svelte/internal/client"),t=require("svelte"),n=require("@embedpdf/models");function r(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}require("svelte/internal/disclose-version");const i=r(e),o=Symbol("pdfEngineContext");function s(){const e=t.getContext(o);if(void 0===e)throw new Error("getPdfEngineContext must be used within a PdfEngineProvider");return e}const l="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm";exports.PdfEngineProvider=function(e,n){i.push(n,!0),i.user_effect(()=>{var e;e={engine:n.engine,isLoading:n.isLoading,error:n.error},t.setContext(o,e)});var r=i.comment(),s=i.first_child(r);i.snippet(s,()=>n.children),i.append(e,r),i.pop()},exports.useEngine=function(){const{engine:e,error:t}=s();if(t)throw t;return e},exports.useEngineContext=function(){const e=s();if(void 0===e)throw new Error("useEngineContext must be used within a PdfEngineProvider");return e},exports.usePdfiumEngine=function(e){const{wasmUrl:t=l,worker:r=!0,logger:o,fontFallback:s}=e??{},d=i.proxy({engine:null,isLoading:!0,error:null});let c=i.state(null);return"undefined"!=typeof window&&i.user_effect(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=r?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),n=await e(t,{logger:o,fontFallback:s});i.set(c,n,!0),d.engine=n,d.isLoading=!1}catch(n){e||(d.error=n,d.isLoading=!1)}})(),()=>{var t,r;e=!0,null==(r=null==(t=i.get(c))?void 0:t.closeAllDocuments)||r.call(t).wait(()=>{var e,t;null==(t=null==(e=i.get(c))?void 0:e.destroy)||t.call(e),i.set(c,null)},n.ignore)}}),d};
1
+ "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("svelte/internal/client"),t=require("svelte"),n=require("@embedpdf/models");function r(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}require("svelte/internal/disclose-version");const i=r(e),o=Symbol("pdfEngineContext");function s(){const e=t.getContext(o);if(void 0===e)throw new Error("getPdfEngineContext must be used within a PdfEngineProvider");return e}const l="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm";exports.PdfEngineProvider=function(e,n){i.push(n,!0),i.user_effect(()=>{var e;e={engine:n.engine,isLoading:n.isLoading,error:n.error},t.setContext(o,e)});var r=i.comment(),s=i.first_child(r);i.snippet(s,()=>n.children),i.append(e,r),i.pop()},exports.useEngine=function(){const{engine:e,error:t}=s();if(t)throw t;return e},exports.useEngineContext=function(){const e=s();if(void 0===e)throw new Error("useEngineContext must be used within a PdfEngineProvider");return e},exports.usePdfiumEngine=function(e){const{wasmUrl:t=l,worker:r=!0,logger:o,fontFallback:s}=e??{},d=i.proxy({engine:null,isLoading:!0,error:null});let c=i.state(null);return"undefined"!=typeof window&&i.user_effect(()=>{let e=!1;return(async()=>{try{const{createPdfiumEngine:e}=r?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),n=await e(t,{logger:o,fontFallback:s});i.set(c,n,!0),d.engine=n,d.isLoading=!1}catch(n){e||(d.error=n,d.isLoading=!1)}})(),()=>{var t,r;e=!0,null==(r=null==(t=i.get(c))?void 0:t.closeAllDocuments)||r.call(t).wait(()=>{var e,t;null==(t=null==(e=i.get(c))?void 0:e.destroy)||t.call(e),i.set(c,null)},n.ignore)}}),d};
2
2
  //# sourceMappingURL=index.cjs.map
@@ -27,7 +27,7 @@ function useEngine() {
27
27
  }
28
28
  return engine;
29
29
  }
30
- const defaultWasmUrl = "https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm";
30
+ const defaultWasmUrl = "https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm";
31
31
  function usePdfiumEngine(config) {
32
32
  const {
33
33
  wasmUrl = defaultWasmUrl,
@@ -1,2 +1,2 @@
1
- "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),n=require("@embedpdf/models"),r=Symbol("pdfEngineKey");function t(){const n=e.inject(r);if(!n)throw new Error("useEngineContext must be used within a PdfEngineProvider");return n}const o="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm";const i=e.defineComponent({__name:"pdf-engine-provider",props:{engine:{},isLoading:{type:Boolean},error:{}},setup(n){const t=n,{engine:o,isLoading:i,error:u}=e.toRefs(t);return e.provide(r,{engine:o,isLoading:i,error:u}),(n,r)=>e.renderSlot(n.$slots,"default")}});exports.PdfEngineProvider=i,exports.useEngine=function(){const{engine:e,error:n}=t();if(n.value)throw n.value;return e},exports.useEngineContext=t,exports.usePdfiumEngine=function(r={}){const{wasmUrl:t=o,worker:i=!0,logger:u,fontFallback:l}=r,s=e.ref(null),a=e.ref(!0),d=e.ref(null);async function c(){try{const{createPdfiumEngine:e}=i?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),n=await e(t,{logger:u,fontFallback:l});s.value=n,a.value=!1}catch(e){d.value=e,a.value=!1}}function p(){var e,r;null==(r=null==(e=s.value)?void 0:e.closeAllDocuments)||r.call(e).wait(()=>{var e,n;null==(n=null==(e=s.value)?void 0:e.destroy)||n.call(e),s.value=null},n.ignore)}return e.onMounted(c),e.onBeforeUnmount(p),e.watch(()=>[t,i,u,l],()=>{p(),c()}),{engine:s,isLoading:a,error:d}};
1
+ "use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue"),n=require("@embedpdf/models"),r=Symbol("pdfEngineKey");function t(){const n=e.inject(r);if(!n)throw new Error("useEngineContext must be used within a PdfEngineProvider");return n}const o="https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm";const i=e.defineComponent({__name:"pdf-engine-provider",props:{engine:{},isLoading:{type:Boolean},error:{}},setup(n){const t=n,{engine:o,isLoading:i,error:u}=e.toRefs(t);return e.provide(r,{engine:o,isLoading:i,error:u}),(n,r)=>e.renderSlot(n.$slots,"default")}});exports.PdfEngineProvider=i,exports.useEngine=function(){const{engine:e,error:n}=t();if(n.value)throw n.value;return e},exports.useEngineContext=t,exports.usePdfiumEngine=function(r={}){const{wasmUrl:t=o,worker:i=!0,logger:u,fontFallback:l}=r,s=e.ref(null),a=e.ref(!0),d=e.ref(null);async function c(){try{const{createPdfiumEngine:e}=i?await import("@embedpdf/engines/pdfium-worker-engine"):await import("@embedpdf/engines/pdfium-direct-engine"),n=await e(t,{logger:u,fontFallback:l});s.value=n,a.value=!1}catch(e){d.value=e,a.value=!1}}function p(){var e,r;null==(r=null==(e=s.value)?void 0:e.closeAllDocuments)||r.call(e).wait(()=>{var e,n;null==(n=null==(e=s.value)?void 0:e.destroy)||n.call(e),s.value=null},n.ignore)}return e.onMounted(c),e.onBeforeUnmount(p),e.watch(()=>[t,i,u,l],()=>{p(),c()}),{engine:s,isLoading:a,error:d}};
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/vue/index.js CHANGED
@@ -15,7 +15,7 @@ function useEngine() {
15
15
  }
16
16
  return engine;
17
17
  }
18
- const defaultWasmUrl = "https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.3.0/dist/pdfium.wasm";
18
+ const defaultWasmUrl = "https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@2.4.1/dist/pdfium.wasm";
19
19
  function usePdfiumEngine(props = {}) {
20
20
  const { wasmUrl = defaultWasmUrl, worker = true, logger, fontFallback } = props;
21
21
  const engine = ref(null);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embedpdf/engines",
3
- "version": "2.3.0",
3
+ "version": "2.4.1",
4
4
  "description": "Pluggable runtime layer that abstracts over multiple PDF engines (PDF-ium, Web Workers, mocks, etc.) to provide a unified API for rendering, search, annotation, and other document-level operations in EmbedPDF.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -90,13 +90,13 @@
90
90
  "dependencies": {
91
91
  "@embedpdf/fonts-arabic": "1.0.0",
92
92
  "@embedpdf/fonts-hebrew": "1.0.0",
93
- "@embedpdf/fonts-jp": "1.0.0",
94
93
  "@embedpdf/fonts-latin": "1.0.0",
95
94
  "@embedpdf/fonts-kr": "1.0.0",
96
- "@embedpdf/models": "2.3.0",
97
95
  "@embedpdf/fonts-sc": "1.0.0",
98
- "@embedpdf/pdfium": "2.3.0",
99
- "@embedpdf/fonts-tc": "1.0.0"
96
+ "@embedpdf/fonts-jp": "1.0.0",
97
+ "@embedpdf/fonts-tc": "1.0.0",
98
+ "@embedpdf/pdfium": "2.4.1",
99
+ "@embedpdf/models": "2.4.1"
100
100
  },
101
101
  "peerDependencies": {
102
102
  "preact": "^10.26.4",
@@ -1,2 +0,0 @@
1
- "use strict";const e=require("@embedpdf/pdfium"),t=require("@embedpdf/models"),o=require("./pdf-engine-DgNNP62W.cjs"),n=require("./browser-C6QEa8uk.cjs");function i(e,t,o,n=100){let i=e.wasmExports.malloc(n);for(let s=0;s<n;s++)e.HEAP8[i+s]=0;const r=t(i,n);let a;if(r>n){e.wasmExports.free(i),i=e.wasmExports.malloc(r);for(let t=0;t<r;t++)e.HEAP8[i+t]=0;t(i,r),a=o(i)}else a=o(i);return e.wasmExports.free(i),a}function r(e,t){const o=t(0,0),n=e.wasmExports.malloc(o);t(n,o);const i=new ArrayBuffer(o),r=new DataView(i);for(let a=0;a<o;a++)r.setInt8(a,e.getValue(n+a,"i8"));return e.wasmExports.free(n),i}const a=new Set(["Title","Author","Subject","Keywords","Producer","Creator","CreationDate","ModDate","Trapped"]);function s(e){if(!e||e.length>127)return!1;if(a.has(e))return!1;if("/"===e[0])return!1;for(let t=0;t<e.length;t++){const o=e.charCodeAt(t);if(o<32||o>126)return!1}return!0}function d(e,o,n,i){const r=o.origin.x,a=o.origin.y,s=r+o.size.width,d=a+o.size.height,l=n.width,u=n.height,h=Math.hypot(e.a,e.b),c=Math.hypot(e.c,e.d),g=!(1&~i),f=g?Math.max(1,Math.round(u*h)):Math.max(1,Math.round(l*h)),m=g?Math.max(1,Math.round(l*c)):Math.max(1,Math.round(u*c));let p,P;switch(i){case t.Rotation.Degree0:p=-Math.round(r*h),P=-Math.round(a*c);break;case t.Rotation.Degree90:p=Math.round((d-u)*h),P=-Math.round(r*c);break;case t.Rotation.Degree180:p=Math.round((s-l)*h),P=Math.round((d-u)*c);break;case t.Rotation.Degree270:p=-Math.round(a*h),P=Math.round((s-l)*c);break;default:p=-Math.round(r*h),P=-Math.round(a*c)}return{startX:p,startY:P,formsWidth:f,formsHeight:m,scaleX:h,scaleY:c}}const l={pageTtl:5e3,maxPagesPerDocument:10};class u{constructor(e,t,o={}){this.pdfium=e,this.memoryManager=t,this.docs=new Map,this.config={...l,...o}}setDocument(e,t,o){let n=this.docs.get(e);n||(n=new h(t,o,this.pdfium,this.memoryManager,this.config),this.docs.set(e,n))}getContext(e){return this.docs.get(e)}closeDocument(e){const t=this.docs.get(e);return!!t&&(t.dispose(),this.docs.delete(e),!0)}closeAllDocuments(){for(const e of this.docs.values())e.dispose();this.docs.clear()}updateConfig(e){Object.assign(this.config,e);for(const t of this.docs.values())t.updateConfig(this.config)}getCacheStats(){const e={};let t=0;for(const[o,n]of this.docs.entries()){const i=n.getCacheSize();e[o]=i,t+=i}return{documents:this.docs.size,totalPages:t,pagesByDocument:e}}}class h{constructor(e,t,o,n,i){this.filePtr=e,this.docPtr=t,this.memoryManager=n,this.pageCache=new c(o,t,i)}acquirePage(e){return this.pageCache.acquire(e)}borrowPage(e,t){return this.pageCache.borrowPage(e,t)}updateConfig(e){this.pageCache.updateConfig(e)}getCacheSize(){return this.pageCache.size()}dispose(){this.pageCache.forceReleaseAll(),this.pageCache.pdf.FPDF_CloseDocument(this.docPtr),this.memoryManager.free(this.filePtr)}}class c{constructor(e,t,o){this.pdf=e,this.docPtr=t,this.cache=new Map,this.accessOrder=[],this.config=o}acquire(e){let t=this.cache.get(e);if(!t){this.evictIfNeeded();const o=this.pdf.FPDF_LoadPage(this.docPtr,e);t=new g(this.pdf,this.docPtr,e,o,this.config.pageTtl,()=>{this.cache.delete(e),this.removeFromAccessOrder(e)}),this.cache.set(e,t)}return this.updateAccessOrder(e),t.clearExpiryTimer(),t.bumpRefCount(),t}borrowPage(e,t){const o=this.cache.has(e),n=this.acquire(e);try{return t(n)}finally{o?n.release():n.disposeImmediate()}}forceReleaseAll(){for(const e of this.cache.values())e.disposeImmediate();this.cache.clear(),this.accessOrder.length=0}updateConfig(e){this.config=e;for(const t of this.cache.values())t.updateTtl(e.pageTtl);this.evictIfNeeded()}size(){return this.cache.size}evictIfNeeded(){for(;this.cache.size>=this.config.maxPagesPerDocument;){const e=this.accessOrder[0];if(void 0===e)break;{const t=this.cache.get(e);if(t){if(0!==t.getRefCount())break;t.disposeImmediate()}else this.removeFromAccessOrder(e)}}}updateAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}}class g{constructor(e,t,o,n,i,r){this.pdf=e,this.docPtr=t,this.pageIdx=o,this.pagePtr=n,this.onFinalDispose=r,this.refCount=0,this.disposed=!1,this.ttl=i}bumpRefCount(){if(this.disposed)throw new Error("Context already disposed");this.refCount++}getRefCount(){return this.refCount}clearExpiryTimer(){this.expiryTimer&&(clearTimeout(this.expiryTimer),this.expiryTimer=void 0)}updateTtl(e){this.ttl=e,this.expiryTimer&&0===this.refCount&&(this.clearExpiryTimer(),this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl))}release(){this.disposed||(this.refCount--,0===this.refCount&&(this.expiryTimer=setTimeout(()=>this.disposeImmediate(),this.ttl)))}disposeImmediate(){this.disposed||(this.disposed=!0,this.clearExpiryTimer(),void 0!==this.textPagePtr&&this.pdf.FPDFText_ClosePage(this.textPagePtr),void 0!==this.formHandle&&(this.pdf.FORM_OnBeforeClosePage(this.pagePtr,this.formHandle),this.pdf.PDFiumExt_ExitFormFillEnvironment(this.formHandle)),void 0!==this.formInfoPtr&&this.pdf.PDFiumExt_CloseFormFillInfo(this.formInfoPtr),this.pdf.FPDF_ClosePage(this.pagePtr),this.onFinalDispose())}getTextPage(){return this.ensureAlive(),void 0===this.textPagePtr&&(this.textPagePtr=this.pdf.FPDFText_LoadPage(this.pagePtr)),this.textPagePtr}getFormHandle(){return this.ensureAlive(),void 0===this.formHandle&&(this.formInfoPtr=this.pdf.PDFiumExt_OpenFormFillInfo(),this.formHandle=this.pdf.PDFiumExt_InitFormFillEnvironment(this.docPtr,this.formInfoPtr),this.pdf.FORM_OnAfterLoadPage(this.pagePtr,this.formHandle)),this.formHandle}withAnnotation(e,t){this.ensureAlive();const o=this.pdf.FPDFPage_GetAnnot(this.pagePtr,e);try{return t(o)}finally{this.pdf.FPDFPage_CloseAnnot(o)}}ensureAlive(){if(this.disposed)throw new Error("PageContext already disposed")}}const f={MAX_TOTAL_MEMORY:2147483648},m="PDFiumEngine",p="MemoryManager";class P{constructor(e,t){this.pdfiumModule=e,this.logger=t,this.allocations=new Map,this.totalAllocated=0}malloc(e){if(this.totalAllocated+e>f.MAX_TOTAL_MEMORY)throw new Error(`Total memory usage would exceed limit: ${this.totalAllocated+e} > ${f.MAX_TOTAL_MEMORY}`);const t=this.pdfiumModule.pdfium.wasmExports.malloc(e);if(!t)throw new Error(`Failed to allocate ${e} bytes`);const o={ptr:t,size:e,timestamp:Date.now(),stack:this.logger.isEnabled("debug")?(new Error).stack:void 0};return this.allocations.set(t,o),this.totalAllocated+=e,t}free(e){const t=this.allocations.get(e);t?(this.totalAllocated-=t.size,this.allocations.delete(e)):this.logger.warn(m,p,`Freeing untracked pointer: ${e}`),this.pdfiumModule.pdfium.wasmExports.free(e)}getStats(){return{totalAllocated:this.totalAllocated,allocationCount:this.allocations.size,allocations:this.logger.isEnabled("debug")?Array.from(this.allocations.values()):[]}}checkLeaks(){if(this.allocations.size>0){this.logger.warn(m,p,`Potential memory leak: ${this.allocations.size} unfreed allocations`);for(const[e,t]of this.allocations)this.logger.warn(m,p,` - ${e}: ${t.size} bytes`,t.stack)}}}const F="pdfium",M="font-fallback";class y{constructor(e,o=new t.NoopLogger){this.fontHandles=new Map,this.fontCache=new Map,this.nextHandleId=1,this.module=null,this.enabled=!1,this.structPtr=0,this.releaseFnPtr=0,this.enumFontsFnPtr=0,this.mapFontFnPtr=0,this.getFontFnPtr=0,this.getFontDataFnPtr=0,this.getFaceNameFnPtr=0,this.getFontCharsetFnPtr=0,this.deleteFontFnPtr=0,this.fontConfig=e,this.logger=o}initialize(e){if(this.enabled)return void this.logger.warn(F,M,"Font fallback already initialized");this.module=e;const t=e.pdfium;if("function"==typeof t.addFunction)try{if(this.structPtr=t.wasmExports.malloc(36),!this.structPtr)throw new Error("Failed to allocate FPDF_SYSFONTINFO struct");for(let e=0;e<36;e++)t.setValue(this.structPtr+e,0,"i8");this.releaseFnPtr=t.addFunction(e=>{},"vi"),this.enumFontsFnPtr=t.addFunction((e,t)=>{},"vii"),this.mapFontFnPtr=t.addFunction((e,o,n,i,r,a,s)=>{const d=a?t.UTF8ToString(a):"",l=this.mapFont(o,n,i,r,d);return s&&t.setValue(s,0,"i32"),l},"iiiiiiii"),this.getFontFnPtr=t.addFunction((e,o)=>{const n=o?t.UTF8ToString(o):"";return this.mapFont(400,0,0,0,n)},"iii"),this.getFontDataFnPtr=t.addFunction((e,t,o,n,i)=>this.getFontData(t,o,n,i),"iiiiii"),this.getFaceNameFnPtr=t.addFunction((e,t,o,n)=>0,"iiiii"),this.getFontCharsetFnPtr=t.addFunction((e,t)=>{const o=this.fontHandles.get(t);return(null==o?void 0:o.charset)??0},"iii"),this.deleteFontFnPtr=t.addFunction((e,t)=>{this.deleteFont(t)},"vii"),t.setValue(this.structPtr+0,1,"i32"),t.setValue(this.structPtr+4,this.releaseFnPtr,"i32"),t.setValue(this.structPtr+8,this.enumFontsFnPtr,"i32"),t.setValue(this.structPtr+12,this.mapFontFnPtr,"i32"),t.setValue(this.structPtr+16,this.getFontFnPtr,"i32"),t.setValue(this.structPtr+20,this.getFontDataFnPtr,"i32"),t.setValue(this.structPtr+24,this.getFaceNameFnPtr,"i32"),t.setValue(this.structPtr+28,this.getFontCharsetFnPtr,"i32"),t.setValue(this.structPtr+32,this.deleteFontFnPtr,"i32"),e.FPDF_SetSystemFontInfo(this.structPtr),this.enabled=!0,this.logger.info(F,M,"Font fallback system initialized (pure TypeScript)",Object.keys(this.fontConfig.fonts))}catch(o){throw this.logger.error(F,M,"Failed to initialize font fallback",o),this.cleanup(),o}else this.logger.error(F,M,"addFunction not available. Make sure WASM is compiled with -sALLOW_TABLE_GROWTH")}disable(){this.enabled&&this.module&&(this.module.FPDF_SetSystemFontInfo(0),this.cleanup(),this.enabled=!1,this.logger.debug(F,M,"Font fallback system disabled"))}cleanup(){if(!this.module)return;const e=this.module.pdfium;this.structPtr&&(e.wasmExports.free(this.structPtr),this.structPtr=0);const t=t=>{if(t&&"function"==typeof e.removeFunction)try{e.removeFunction(t)}catch{}};t(this.releaseFnPtr),t(this.enumFontsFnPtr),t(this.mapFontFnPtr),t(this.getFontFnPtr),t(this.getFontDataFnPtr),t(this.getFaceNameFnPtr),t(this.getFontCharsetFnPtr),t(this.deleteFontFnPtr),this.releaseFnPtr=0,this.enumFontsFnPtr=0,this.mapFontFnPtr=0,this.getFontFnPtr=0,this.getFontDataFnPtr=0,this.getFaceNameFnPtr=0,this.getFontCharsetFnPtr=0,this.deleteFontFnPtr=0}isEnabled(){return this.enabled}getStats(){return{handleCount:this.fontHandles.size,cacheSize:this.fontCache.size,cachedUrls:Array.from(this.fontCache.keys())}}async preloadFonts(e){const t=e.map(e=>this.getFontUrlForCharset(e)).filter(e=>null!==e),o=[...new Set(t)];await Promise.all(o.map(async e=>{if(!this.fontCache.has(e))try{const t=await this.fetchFontAsync(e);t&&(this.fontCache.set(e,t),this.logger.debug(F,M,`Pre-loaded font: ${e}`))}catch(t){this.logger.warn(F,M,`Failed to pre-load font: ${e}`,t)}}))}mapFont(e,t,o,n,i){const r=0!==t;this.logger.debug(F,M,"MapFont called",{weight:e,italic:r,charset:o,pitchFamily:n,face:i});const a=this.findBestFontMatch(o,e,r);if(!a)return this.logger.debug(F,M,`No font configured for charset ${o}`),0;const s={id:this.nextHandleId++,charset:o,weight:e,italic:r,url:a.url,data:null};return this.fontHandles.set(s.id,s),this.logger.debug(F,M,`Created font handle ${s.id} for ${a.url} (requested: weight=${e}, italic=${r}, matched: weight=${a.matchedWeight}, italic=${a.matchedItalic})`),s.id}getFontData(e,t,o,n){const i=this.fontHandles.get(e);if(!i)return this.logger.warn(F,M,`Unknown font handle: ${e}`),0;if(i.data||(this.fontCache.has(i.url)?i.data=this.fontCache.get(i.url):(i.data=this.fetchFontSync(i.url),i.data&&this.fontCache.set(i.url,i.data))),!i.data)return this.logger.warn(F,M,`Failed to load font: ${i.url}`),0;const r=i.data;if(0!==t)return this.logger.debug(F,M,`Table ${t} requested - returning 0 to request whole file`),0;if(0===o||n<r.length)return r.length;if(this.module){this.module.pdfium.HEAPU8.set(r,o),this.logger.debug(F,M,`Copied ${r.length} bytes to buffer for handle ${e}`)}return r.length}deleteFont(e){this.fontHandles.get(e)&&(this.logger.debug(F,M,`Deleting font handle ${e}`),this.fontHandles.delete(e))}findBestFontMatch(e,t,o){const{fonts:n,defaultFont:i,baseUrl:r}=this.fontConfig,a=n[e]??i;if(!a)return null;const s=this.normalizeToVariants(a);if(0===s.length)return null;const d=this.selectBestVariant(s,t,o);let l=d.url;return!r||l.startsWith("http://")||l.startsWith("https://")||l.startsWith("/")||(l=`${r}/${l}`),{url:l,matchedWeight:d.weight??400,matchedItalic:d.italic??!1}}normalizeToVariants(e){return"string"==typeof e?[{url:e,weight:400,italic:!1}]:Array.isArray(e)?e.map(e=>({url:e.url,weight:e.weight??400,italic:e.italic??!1})):[{url:e.url,weight:e.weight??400,italic:e.italic??!1}]}selectBestVariant(e,t,o){if(1===e.length)return e[0];const n=e.filter(e=>(e.italic??!1)===o),i=n.length>0?n:e;let r=i[0],a=Math.abs((r.weight??400)-t);for(const s of i){const e=s.weight??400,o=Math.abs(e-t);if(o<a)r=s,a=o;else if(o===a){const o=r.weight??400;t>=500?e>o&&(r=s):e<o&&(r=s)}}return r}getFontUrlForCharset(e){const t=this.findBestFontMatch(e,400,!1);return(null==t?void 0:t.url)??null}fetchFontSync(e){if(this.logger.debug(F,M,`Fetching font synchronously: ${e}`),this.fontConfig.fontLoader)try{const t=this.fontConfig.fontLoader(e);return t?this.logger.info(F,M,`Loaded font via custom loader: ${e} (${t.length} bytes)`):this.logger.warn(F,M,`Custom font loader returned null for: ${e}`),t}catch(t){return this.logger.error(F,M,`Error in custom font loader: ${e}`,t),null}try{const t=new XMLHttpRequest;if(t.open("GET",e,!1),t.responseType="arraybuffer",t.send(),200===t.status){const o=new Uint8Array(t.response);return this.logger.info(F,M,`Loaded font: ${e} (${o.length} bytes)`),o}return this.logger.error(F,M,`Failed to load font: ${e} (HTTP ${t.status})`),null}catch(t){return this.logger.error(F,M,`Error fetching font: ${e}`,t),null}}async fetchFontAsync(e){if(this.fontConfig.fontLoader)try{return this.fontConfig.fontLoader(e)}catch{return null}try{const t=await fetch(e);if(t.ok){const e=await t.arrayBuffer();return new Uint8Array(e)}return null}catch{return null}}}var A=(e=>(e[e.Bitmap_Gray=1]="Bitmap_Gray",e[e.Bitmap_BGR=2]="Bitmap_BGR",e[e.Bitmap_BGRx=3]="Bitmap_BGRx",e[e.Bitmap_BGRA=4]="Bitmap_BGRA",e))(A||{}),D=(e=>(e[e.ANNOT=1]="ANNOT",e[e.LCD_TEXT=2]="LCD_TEXT",e[e.NO_NATIVETEXT=4]="NO_NATIVETEXT",e[e.GRAYSCALE=8]="GRAYSCALE",e[e.DEBUG_INFO=128]="DEBUG_INFO",e[e.NO_CATCH=256]="NO_CATCH",e[e.RENDER_LIMITEDIMAGECACHE=512]="RENDER_LIMITEDIMAGECACHE",e[e.RENDER_FORCEHALFTONE=1024]="RENDER_FORCEHALFTONE",e[e.PRINTING=2048]="PRINTING",e[e.REVERSE_BYTE_ORDER=16]="REVERSE_BYTE_ORDER",e))(D||{});const T="PDFiumEngine",C="Engine";var E=(e=>(e[e.Success=0]="Success",e[e.Unknown=1]="Unknown",e[e.File=2]="File",e[e.Format=3]="Format",e[e.Password=4]="Password",e[e.Security=5]="Security",e[e.Page=6]="Page",e[e.XFALoad=7]="XFALoad",e[e.XFALayout=8]="XFALayout",e))(E||{});class x{constructor(e,o={}){this.pdfiumModule=e,this.memoryLeakCheckInterval=null,this.fontFallbackManager=null;const{logger:n=new t.NoopLogger,fontFallback:i}=o;this.logger=n,this.memoryManager=new P(this.pdfiumModule,this.logger),this.cache=new u(this.pdfiumModule,this.memoryManager),this.logger.isEnabled("debug")&&(this.memoryLeakCheckInterval=setInterval(()=>{this.memoryManager.checkLeaks()},1e4)),this.logger.debug(T,C,"initialize"),this.logger.perf(T,C,"Initialize","Begin","General"),this.pdfiumModule.PDFiumExt_Init(),this.logger.perf(T,C,"Initialize","End","General"),i&&(this.fontFallbackManager=new y(i,this.logger),this.fontFallbackManager.initialize(this.pdfiumModule),this.logger.info(T,C,"Font fallback system enabled"))}destroy(){return this.logger.debug(T,C,"destroy"),this.logger.perf(T,C,"Destroy","Begin","General"),this.fontFallbackManager&&(this.fontFallbackManager.disable(),this.fontFallbackManager=null),this.pdfiumModule.FPDF_DestroyLibrary(),this.memoryLeakCheckInterval&&(clearInterval(this.memoryLeakCheckInterval),this.memoryLeakCheckInterval=null),this.logger.perf(T,C,"Destroy","End","General"),t.PdfTaskHelper.resolve(!0)}getFontFallbackManager(){return this.fontFallbackManager}withWString(e,t){const o=2*(e.length+1),n=this.memoryManager.malloc(o);try{return this.pdfiumModule.pdfium.stringToUTF16(e,n,o),t(n)}finally{this.memoryManager.free(n)}}withFloatArray(e,t){const o=e??[],n=4*o.length,i=n?this.memoryManager.malloc(n):0;try{if(n)for(let e=0;e<o.length;e++)this.pdfiumModule.pdfium.setValue(i+4*e,o[e],"float");return t(i,o.length)}finally{n&&this.memoryManager.free(i)}}openDocumentBuffer(e,o){this.logger.debug(T,C,"openDocumentBuffer",e,o),this.logger.perf(T,C,"OpenDocumentBuffer","Begin",e.id);const n=new Uint8Array(e.content),i=n.length,r=this.memoryManager.malloc(i);this.pdfiumModule.pdfium.HEAPU8.set(n,r);const a=this.pdfiumModule.FPDF_LoadMemDocument(r,i,(null==o?void 0:o.password)??"");if(!a){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(T,C,`FPDF_LoadMemDocument failed with ${o}`),this.memoryManager.free(r),this.logger.perf(T,C,"OpenDocumentBuffer","End",e.id),t.PdfTaskHelper.reject({code:o,message:"FPDF_LoadMemDocument failed"})}const s=this.pdfiumModule.FPDF_GetPageCount(a),d=[],l=this.memoryManager.malloc(8);for(let f=0;f<s;f++){if(!this.pdfiumModule.FPDF_GetPageSizeByIndexF(a,f,l)){const o=this.pdfiumModule.FPDF_GetLastError();return this.logger.error(T,C,`FPDF_GetPageSizeByIndexF failed with ${o}`),this.memoryManager.free(l),this.pdfiumModule.FPDF_CloseDocument(a),this.memoryManager.free(r),this.logger.perf(T,C,"OpenDocumentBuffer","End",e.id),t.PdfTaskHelper.reject({code:o,message:"FPDF_GetPageSizeByIndexF failed"})}const o=this.pdfiumModule.EPDF_GetPageRotationByIndex(a,f),n={index:f,size:{width:this.pdfiumModule.pdfium.getValue(l,"float"),height:this.pdfiumModule.pdfium.getValue(l+4,"float")},rotation:o};d.push(n)}this.memoryManager.free(l);const u=this.pdfiumModule.EPDF_IsEncrypted(a),h=this.pdfiumModule.EPDF_IsOwnerUnlocked(a),c=this.pdfiumModule.FPDF_GetDocPermissions(a),g={id:e.id,pageCount:s,pages:d,isEncrypted:u,isOwnerUnlocked:h,permissions:c};return this.cache.setDocument(e.id,r,a),this.logger.perf(T,C,"OpenDocumentBuffer","End",e.id),t.PdfTaskHelper.resolve(g)}getMetadata(e){this.logger.debug(T,C,"getMetadata",e),this.logger.perf(T,C,"GetMetadata","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"GetMetadata","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.readMetaText(o.docPtr,"CreationDate"),i=this.readMetaText(o.docPtr,"ModDate"),r={title:this.readMetaText(o.docPtr,"Title"),author:this.readMetaText(o.docPtr,"Author"),subject:this.readMetaText(o.docPtr,"Subject"),keywords:this.readMetaText(o.docPtr,"Keywords"),producer:this.readMetaText(o.docPtr,"Producer"),creator:this.readMetaText(o.docPtr,"Creator"),creationDate:n?t.pdfDateToDate(n)??null:null,modificationDate:i?t.pdfDateToDate(i)??null:null,trapped:this.getMetaTrapped(o.docPtr),custom:this.readAllMeta(o.docPtr,!0)};return this.logger.perf(T,C,"GetMetadata","End",e.id),t.PdfTaskHelper.resolve(r)}setMetadata(e,o){this.logger.debug(T,C,"setMetadata",e,o),this.logger.perf(T,C,"SetMetadata","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"SetMetadata","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=[["title","Title"],["author","Author"],["subject","Subject"],["keywords","Keywords"],["producer","Producer"],["creator","Creator"]];let r=!0;for(const[t,s]of i){const e=o[t];if(void 0===e)continue;const i=null===e?null:e;this.setMetaText(n.docPtr,s,i)||(r=!1)}const a=(e,i)=>{const a=o[e];if(void 0===a)return;if(null===a)return void(this.setMetaText(n.docPtr,i,null)||(r=!1));const s=a,d=t.dateToPdfDate(s);this.setMetaText(n.docPtr,i,d)||(r=!1)};if(a("creationDate","CreationDate"),a("modificationDate","ModDate"),void 0!==o.trapped&&(this.setMetaTrapped(n.docPtr,o.trapped??null)||(r=!1)),void 0!==o.custom)for(const[t,d]of Object.entries(o.custom))s(t)?this.setMetaText(n.docPtr,t,d??null)||(r=!1):this.logger.warn(T,C,"Invalid custom metadata key skipped",t);return this.logger.perf(T,C,"SetMetadata","End",e.id),r?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"one or more metadata fields could not be written"})}getDocPermissions(e){this.logger.debug(T,C,"getDocPermissions",e),this.logger.perf(T,C,"getDocPermissions","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"getDocPermissions","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_GetDocPermissions(o.docPtr);return t.PdfTaskHelper.resolve(n)}getDocUserPermissions(e){this.logger.debug(T,C,"getDocUserPermissions",e),this.logger.perf(T,C,"getDocUserPermissions","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"getDocUserPermissions","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.FPDF_GetDocUserPermissions(o.docPtr);return t.PdfTaskHelper.resolve(n)}getSignatures(e){this.logger.debug(T,C,"getSignatures",e),this.logger.perf(T,C,"GetSignatures","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"GetSignatures","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[],a=this.pdfiumModule.FPDF_GetSignatureCount(o.docPtr);for(let t=0;t<a;t++){const e=this.pdfiumModule.FPDF_GetSignatureObject(o.docPtr,t),a=r(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetContents(e,t,o)),s=r(this.pdfiumModule.pdfium,(t,o)=>4*this.pdfiumModule.FPDFSignatureObj_GetByteRange(e,t,o)),d=r(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetSubFilter(e,t,o)),l=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetReason(e,t,o),this.pdfiumModule.pdfium.UTF16ToString),u=i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.FPDFSignatureObj_GetTime(e,t,o),this.pdfiumModule.pdfium.UTF8ToString),h=this.pdfiumModule.FPDFSignatureObj_GetDocMDPPermission(e);n.push({contents:a,byteRange:s,subFilter:d,reason:l,time:u,docMDP:h})}return this.logger.perf(T,C,"GetSignatures","End",e.id),t.PdfTaskHelper.resolve(n)}getBookmarks(e){this.logger.debug(T,C,"getBookmarks",e),this.logger.perf(T,C,"GetBookmarks","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"getBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.readPdfBookmarks(o.docPtr,0);return this.logger.perf(T,C,"GetBookmarks","End",e.id),t.PdfTaskHelper.resolve({bookmarks:n})}setBookmarks(e,o){this.logger.debug(T,C,"setBookmarks",e,o),this.logger.perf(T,C,"SetBookmarks","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"SetBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});if(!this.pdfiumModule.EPDFBookmark_Clear(n.docPtr))return this.logger.perf(T,C,"SetBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to clear existing bookmarks"});const i=(e,t)=>{var o;for(const r of t){const t=this.withWString(r.title??"",t=>this.pdfiumModule.EPDFBookmark_AppendChild(n.docPtr,e,t));if(!t)return!1;if(r.target){if(!this.applyBookmarkTarget(n.docPtr,t,r.target))return!1}if(null==(o=r.children)?void 0:o.length){if(!i(t,r.children))return!1}}return!0},r=i(0,o);return this.logger.perf(T,C,"SetBookmarks","End",e.id),r?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to build bookmark tree"})}deleteBookmarks(e){this.logger.debug(T,C,"deleteBookmarks",e),this.logger.perf(T,C,"DeleteBookmarks","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"DeleteBookmarks","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDFBookmark_Clear(o.docPtr);return this.logger.perf(T,C,"DeleteBookmarks","End",e.id),n?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to clear bookmarks"})}renderPageRaw(e,t,o){this.logger.debug(T,C,"renderPage",e,t,o),this.logger.perf(T,C,"RenderPage","Begin",`${e.id}-${t.index}`);const n={origin:{x:0,y:0},size:t.size},i=this.renderRectEncoded(e,t,n,o);return this.logger.perf(T,C,"RenderPage","End",`${e.id}-${t.index}`),i}renderPageRect(e,t,o,n){this.logger.debug(T,C,"renderPageRect",e,t,o,n),this.logger.perf(T,C,"RenderPageRect","Begin",`${e.id}-${t.index}`);const i=this.renderRectEncoded(e,t,o,n);return this.logger.perf(T,C,"RenderPageRect","End",`${e.id}-${t.index}`),i}getPageAnnotations(e,o){this.logger.debug(T,C,"getPageAnnotations",e,o),this.logger.perf(T,C,"GetPageAnnotations","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"GetPageAnnotations","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readPageAnnotations(n,o);return this.logger.perf(T,C,"GetPageAnnotations","End",`${e.id}-${o.index}`),this.logger.debug(T,C,"GetPageAnnotations",`${e.id}-${o.index}`,i),t.PdfTaskHelper.resolve(i)}createPageAnnotation(e,o,n,i){this.logger.debug(T,C,"createPageAnnotation",e,o,n),this.logger.perf(T,C,"CreatePageAnnotation","Begin",`${e.id}-${o.index}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(T,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.pdfiumModule.EPDFPage_CreateAnnot(a.pagePtr,n.type);if(!s)return this.logger.perf(T,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),a.release(),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateAnnot,message:"can not create annotation with specified type"});if(t.isUuidV4(n.id)||(n.id=t.uuidV4()),!this.setAnnotString(s,"NM",n.id))return this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotString,message:"can not set the name of the annotation"});if(!this.setPageAnnoRect(o,s,n.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),this.logger.perf(T,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotRect,message:"can not set the rect of the annotation"});let d=!1;switch(n.type){case t.PdfAnnotationSubtype.INK:d=this.addInkStroke(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.STAMP:d=this.addStampContent(r.docPtr,o,a.pagePtr,s,n,null==i?void 0:i.imageData);break;case t.PdfAnnotationSubtype.TEXT:d=this.addTextContent(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.FREETEXT:d=this.addFreeTextContent(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.LINE:d=this.addLineContent(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.POLYLINE:case t.PdfAnnotationSubtype.POLYGON:d=this.addPolyContent(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.CIRCLE:case t.PdfAnnotationSubtype.SQUARE:d=this.addShapeContent(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.UNDERLINE:case t.PdfAnnotationSubtype.STRIKEOUT:case t.PdfAnnotationSubtype.SQUIGGLY:case t.PdfAnnotationSubtype.HIGHLIGHT:d=this.addTextMarkupContent(o,a.pagePtr,s,n);break;case t.PdfAnnotationSubtype.LINK:d=this.addLinkContent(r.docPtr,a.pagePtr,s,n)}return d?(void 0!==n.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(s,n.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(s),this.pdfiumModule.FPDFPage_GenerateContent(a.pagePtr),this.pdfiumModule.FPDFPage_CloseAnnot(s),a.release(),this.logger.perf(T,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(n.id)):(this.pdfiumModule.FPDFPage_RemoveAnnot(a.pagePtr,s),a.release(),this.logger.perf(T,C,"CreatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotContent,message:"can not add content of the annotation"}))}updatePageAnnotation(e,o,n){this.logger.debug(T,C,"updatePageAnnotation",e,o,n),this.logger.perf(T,C,"UpdatePageAnnotation","Begin",`${e.id}-${o.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(T,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index),a=this.getAnnotationByName(r.pagePtr,n.id);if(!a)return r.release(),this.logger.perf(T,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.setPageAnnoRect(o,a,n.rect))return this.pdfiumModule.FPDFPage_CloseAnnot(a),r.release(),this.logger.perf(T,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotRect,message:"failed to move annotation"});let s=!1;switch(n.type){case t.PdfAnnotationSubtype.INK:if(!this.pdfiumModule.FPDFAnnot_RemoveInkList(a))break;s=this.addInkStroke(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.STAMP:s=this.addStampContent(i.docPtr,o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.TEXT:s=this.addTextContent(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.FREETEXT:s=this.addFreeTextContent(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.CIRCLE:case t.PdfAnnotationSubtype.SQUARE:s=this.addShapeContent(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.LINE:s=this.addLineContent(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.POLYGON:case t.PdfAnnotationSubtype.POLYLINE:s=this.addPolyContent(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.HIGHLIGHT:case t.PdfAnnotationSubtype.UNDERLINE:case t.PdfAnnotationSubtype.STRIKEOUT:case t.PdfAnnotationSubtype.SQUIGGLY:s=this.addTextMarkupContent(o,r.pagePtr,a,n);break;case t.PdfAnnotationSubtype.LINK:s=this.addLinkContent(i.docPtr,r.pagePtr,a,n);break;default:s=!1}return s&&(void 0!==n.blendMode?this.pdfiumModule.EPDFAnnot_GenerateAppearanceWithBlend(a,n.blendMode):this.pdfiumModule.EPDFAnnot_GenerateAppearance(a),this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr)),this.pdfiumModule.FPDFPage_CloseAnnot(a),r.release(),this.logger.perf(T,C,"UpdatePageAnnotation","End",`${e.id}-${o.index}`),s?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSetAnnotContent,message:"failed to update annotation"})}removePageAnnotation(e,o,n){this.logger.debug(T,C,"removePageAnnotation",e,o,n),this.logger.perf(T,C,"RemovePageAnnotation","Begin",`${e.id}-${o.index}`);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(T,C,"RemovePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index);let a=!1;return a=this.removeAnnotationByName(r.pagePtr,n.id),a?(a=this.pdfiumModule.FPDFPage_GenerateContent(r.pagePtr),a||this.logger.error(T,C,"FPDFPage_GenerateContent Failed",`${e.id}-${o.index}`)):this.logger.error(T,C,"FPDFPage_RemoveAnnot Failed",`${e.id}-${o.index}`),r.release(),this.logger.perf(T,C,"RemovePageAnnotation","End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(a)}getPageTextRects(e,o){this.logger.debug(T,C,"getPageTextRects",e,o),this.logger.perf(T,C,"GetPageTextRects","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"GetPageTextRects","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=n.acquirePage(o.index),r=this.pdfiumModule.FPDFText_LoadPage(i.pagePtr),a=this.readPageTextRects(o,i.docPtr,i.pagePtr,r);return this.pdfiumModule.FPDFText_ClosePage(r),i.release(),this.logger.perf(T,C,"GetPageTextRects","End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(a)}renderThumbnailRaw(e,o,n){const{scaleFactor:i=1,...r}=n??{};this.logger.debug(T,C,"renderThumbnail",e,o,n),this.logger.perf(T,C,"RenderThumbnail","Begin",`${e.id}-${o.index}`);if(!this.cache.getContext(e.id))return this.logger.perf(T,C,"RenderThumbnail","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.renderPageRaw(e,o,{scaleFactor:Math.max(i,.5),...r});return this.logger.perf(T,C,"RenderThumbnail","End",`${e.id}-${o.index}`),a}getAttachments(e){this.logger.debug(T,C,"getAttachments",e),this.logger.perf(T,C,"GetAttachments","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"GetAttachments","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=[],i=this.pdfiumModule.FPDFDoc_GetAttachmentCount(o.docPtr);for(let t=0;t<i;t++){const e=this.readPdfAttachment(o.docPtr,t);n.push(e)}return this.logger.perf(T,C,"GetAttachments","End",e.id),t.PdfTaskHelper.resolve(n)}addAttachment(e,o){this.logger.debug(T,C,"addAttachment",e,null==o?void 0:o.name),this.logger.perf(T,C,"AddAttachment","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const{name:i,description:r,mimeType:a,data:s}=o??{};if(!i)return this.logger.perf(T,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"attachment name is required"});if(!s||(Uint8Array,0===s.byteLength))return this.logger.perf(T,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"attachment data is empty"});const d=this.withWString(i,e=>this.pdfiumModule.FPDFDoc_AddAttachment(n.docPtr,e));if(!d)return this.logger.perf(T,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:`An attachment named "${i}" already exists`});this.withWString(r,e=>this.pdfiumModule.EPDFAttachment_SetDescription(d,e)),this.pdfiumModule.EPDFAttachment_SetSubtype(d,a);const l=s instanceof Uint8Array?s:new Uint8Array(s),u=l.byteLength,h=this.memoryManager.malloc(u);try{this.pdfiumModule.pdfium.HEAPU8.set(l,h);if(!this.pdfiumModule.FPDFAttachment_SetFile(d,n.docPtr,h,u))return this.logger.perf(T,C,"AddAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to write attachment bytes"})}finally{this.memoryManager.free(h)}return this.logger.perf(T,C,"AddAttachment","End",e.id),t.PdfTaskHelper.resolve(!0)}removeAttachment(e,o){this.logger.debug(T,C,"deleteAttachment",e,o),this.logger.perf(T,C,"DeleteAttachment","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"DeleteAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDFDoc_GetAttachmentCount(n.docPtr);if(o.index<0||o.index>=i)return this.logger.perf(T,C,"DeleteAttachment","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:`attachment index ${o.index} out of range`});const r=this.pdfiumModule.FPDFDoc_DeleteAttachment(n.docPtr,o.index);return this.logger.perf(T,C,"DeleteAttachment","End",e.id),r?t.PdfTaskHelper.resolve(!0):t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"failed to delete attachment"})}readAttachmentContent(e,o){this.logger.debug(T,C,"readAttachmentContent",e,o),this.logger.perf(T,C,"ReadAttachmentContent","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDFDoc_GetAttachment(n.docPtr,o.index),r=this.memoryManager.malloc(4);if(!this.pdfiumModule.FPDFAttachment_GetFile(i,0,0,r))return this.memoryManager.free(r),this.logger.perf(T,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantReadAttachmentSize,message:"can not read attachment size"});const a=this.pdfiumModule.pdfium.getValue(r,"i32")>>>0,s=this.memoryManager.malloc(a);if(!this.pdfiumModule.FPDFAttachment_GetFile(i,s,a,r))return this.memoryManager.free(r),this.memoryManager.free(s),this.logger.perf(T,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantReadAttachmentContent,message:"can not read attachment content"});const d=new ArrayBuffer(a),l=new DataView(d);for(let t=0;t<a;t++)l.setInt8(t,this.pdfiumModule.pdfium.getValue(s+t,"i8"));return this.memoryManager.free(r),this.memoryManager.free(s),this.logger.perf(T,C,"ReadAttachmentContent","End",e.id),t.PdfTaskHelper.resolve(d)}setFormFieldValue(e,o,n,i){this.logger.debug(T,C,"SetFormFieldValue",e,n,i),this.logger.perf(T,C,"SetFormFieldValue","Begin",`${e.id}-${n.id}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.debug(T,C,"SetFormFieldValue","document is not opened"),this.logger.perf(T,C,"SetFormFieldValue","End",`${e.id}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.PDFiumExt_OpenFormFillInfo(),s=this.pdfiumModule.PDFiumExt_InitFormFillEnvironment(r.docPtr,a),d=r.acquirePage(o.index);this.pdfiumModule.FORM_OnAfterLoadPage(d.pagePtr,s);const l=this.getAnnotationByName(d.pagePtr,n.id);if(!l)return d.release(),this.logger.perf(T,C,"SetFormFieldValue","End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});if(!this.pdfiumModule.FORM_SetFocusedAnnot(s,l))return this.logger.debug(T,C,"SetFormFieldValue","failed to set focused annotation"),this.logger.perf(T,C,"SetFormFieldValue","End",`${e.id}-${n.id}`),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantFocusAnnot,message:"failed to set focused annotation"});switch(i.kind){case"text":{if(!this.pdfiumModule.FORM_SelectAllText(s,d.pagePtr))return this.logger.debug(T,C,"SetFormFieldValue","failed to select all text"),this.logger.perf(T,C,"SetFormFieldValue","End",`${e.id}-${n.id}`),this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectText,message:"failed to select all text"});const o=2*(i.text.length+1),r=this.memoryManager.malloc(o);this.pdfiumModule.pdfium.stringToUTF16(i.text,r,o),this.pdfiumModule.FORM_ReplaceSelection(s,d.pagePtr,r),this.memoryManager.free(r)}break;case"selection":if(!this.pdfiumModule.FORM_SetIndexSelected(s,d.pagePtr,i.index,i.isSelected))return this.logger.debug(T,C,"SetFormFieldValue","failed to set index selected"),this.logger.perf(T,C,"SetFormFieldValue","End",`${e.id}-${n.id}`),this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantSelectOption,message:"failed to set index selected"});break;case"checked":{const o=13;if(!this.pdfiumModule.FORM_OnChar(s,d.pagePtr,o,0))return this.logger.debug(T,C,"SetFormFieldValue","failed to set field checked"),this.logger.perf(T,C,"SetFormFieldValue","End",`${e.id}-${n.id}`),this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCheckField,message:"failed to set field checked"})}}return this.pdfiumModule.FORM_ForceToKillFocus(s),this.pdfiumModule.FPDFPage_CloseAnnot(l),this.pdfiumModule.FORM_OnBeforeClosePage(d.pagePtr,s),d.release(),this.pdfiumModule.PDFiumExt_ExitFormFillEnvironment(s),this.pdfiumModule.PDFiumExt_CloseFormFillInfo(a),t.PdfTaskHelper.resolve(!0)}flattenPage(e,o,n){const{flag:i=t.PdfPageFlattenFlag.Display}=n??{};this.logger.debug(T,C,"flattenPage",e,o,i),this.logger.perf(T,C,"flattenPage","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(T,C,"flattenPage","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=r.acquirePage(o.index),s=this.pdfiumModule.FPDFPage_Flatten(a.pagePtr,i);return a.release(),this.logger.perf(T,C,"flattenPage","End",e.id),t.PdfTaskHelper.resolve(s)}extractPages(e,o){this.logger.debug(T,C,"extractPages",e,o),this.logger.perf(T,C,"ExtractPages","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"ExtractPages","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.FPDF_CreateNewDocument();if(!i)return this.logger.perf(T,C,"ExtractPages","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const r=this.memoryManager.malloc(4*o.length);for(let t=0;t<o.length;t++)this.pdfiumModule.pdfium.setValue(r+4*t,o[t],"i32");if(!this.pdfiumModule.FPDF_ImportPagesByIndex(i,n.docPtr,r,o.length,0))return this.pdfiumModule.FPDF_CloseDocument(i),this.logger.perf(T,C,"ExtractPages","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:"can not import pages to new document"});const a=this.saveDocument(i);return this.pdfiumModule.FPDF_CloseDocument(i),this.logger.perf(T,C,"ExtractPages","End",e.id),t.PdfTaskHelper.resolve(a)}extractText(e,o){this.logger.debug(T,C,"extractText",e,o),this.logger.perf(T,C,"ExtractText","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"ExtractText","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=[];for(let t=0;t<o.length;t++){const e=n.acquirePage(o[t]),r=this.pdfiumModule.FPDFText_LoadPage(e.pagePtr),a=this.pdfiumModule.FPDFText_CountChars(r),s=this.memoryManager.malloc(2*(a+1));this.pdfiumModule.FPDFText_GetText(r,0,a,s);const d=this.pdfiumModule.pdfium.UTF16ToString(s);this.memoryManager.free(s),i.push(d),this.pdfiumModule.FPDFText_ClosePage(r),e.release()}const r=i.join("\n\n");return this.logger.perf(T,C,"ExtractText","End",e.id),t.PdfTaskHelper.resolve(r)}getTextSlices(e,o){if(this.logger.debug(T,C,"getTextSlices",e,o),this.logger.perf(T,C,"GetTextSlices","Begin",e.id),0===o.length)return this.logger.perf(T,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.resolve([]);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});try{const i=new Array(o.length),r=new Map;o.forEach((e,t)=>{(r.get(e.pageIndex)??r.set(e.pageIndex,[]).get(e.pageIndex)).push({slice:e,pos:t})});for(const[e,o]of r){const r=n.acquirePage(e),a=r.getTextPage();for(const{slice:e,pos:n}of o){const o=this.memoryManager.malloc(2*(e.charCount+1));this.pdfiumModule.FPDFText_GetText(a,e.charIndex,e.charCount,o),i[n]=t.stripPdfUnwantedMarkers(this.pdfiumModule.pdfium.UTF16ToString(o)),this.memoryManager.free(o)}r.release()}return this.logger.perf(T,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.resolve(i)}catch(i){return this.logger.error(T,C,"getTextSlices error",i),this.logger.perf(T,C,"GetTextSlices","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:String(i)})}}merge(e){this.logger.debug(T,C,"merge",e);const o=e.map(e=>e.id).join(".");this.logger.perf(T,C,"Merge","Begin",o);const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(T,C,"Merge","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"can not create new document"});const i=[];for(const s of e.reverse()){const e=new Uint8Array(s.content),r=e.length,a=this.memoryManager.malloc(r);this.pdfiumModule.pdfium.HEAPU8.set(e,a);const d=this.pdfiumModule.FPDF_LoadMemDocument(a,r,"");if(!d){const e=this.pdfiumModule.FPDF_GetLastError();this.logger.error(T,C,`FPDF_LoadMemDocument failed with ${e}`),this.memoryManager.free(a);for(const t of i)this.pdfiumModule.FPDF_CloseDocument(t.docPtr),this.memoryManager.free(t.filePtr);return this.logger.perf(T,C,"Merge","End",o),t.PdfTaskHelper.reject({code:e,message:"FPDF_LoadMemDocument failed"})}if(i.push({filePtr:a,docPtr:d}),!this.pdfiumModule.FPDF_ImportPages(n,d,"",0)){this.pdfiumModule.FPDF_CloseDocument(n);for(const e of i)this.pdfiumModule.FPDF_CloseDocument(e.docPtr),this.memoryManager.free(e.filePtr);return this.logger.perf(T,C,"Merge","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:"can not import pages to new document"})}}const r=this.saveDocument(n);this.pdfiumModule.FPDF_CloseDocument(n);for(const t of i)this.pdfiumModule.FPDF_CloseDocument(t.docPtr),this.memoryManager.free(t.filePtr);const a={id:`${Math.random()}`,content:r};return this.logger.perf(T,C,"Merge","End",o),t.PdfTaskHelper.resolve(a)}mergePages(e){const o=e.map(e=>`${e.docId}:${e.pageIndices.join(",")}`).join("|");this.logger.debug(T,C,"mergePages",e),this.logger.perf(T,C,"MergePages","Begin",o);const n=this.pdfiumModule.FPDF_CreateNewDocument();if(!n)return this.logger.perf(T,C,"MergePages","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"Cannot create new document"});try{for(const t of[...e].reverse()){const e=this.cache.getContext(t.docId);if(!e){this.logger.warn(T,C,`Document ${t.docId} is not open, skipping`);continue}const o=this.pdfiumModule.FPDF_GetPageCount(e.docPtr),i=t.pageIndices.filter(e=>e>=0&&e<o);if(0===i.length)continue;const r=i.map(e=>e+1).join(",");try{if(!this.pdfiumModule.FPDF_ImportPages(n,e.docPtr,r,0))throw new Error(`Failed to import pages ${r} from document ${t.docId}`)}finally{}}const i=this.saveDocument(n),r={id:`${Math.random()}`,content:i};return this.logger.perf(T,C,"MergePages","End",o),t.PdfTaskHelper.resolve(r)}catch(i){return this.logger.error(T,C,"mergePages failed",i),this.logger.perf(T,C,"MergePages","End",o),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:i instanceof Error?i.message:"Failed to merge pages"})}finally{n&&this.pdfiumModule.FPDF_CloseDocument(n)}}setDocumentEncryption(e,o,n,i){this.logger.debug(T,C,"setDocumentEncryption",e,i);const r=this.cache.getContext(e.id);if(!r)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const a=this.pdfiumModule.EPDF_SetEncryption(r.docPtr,o,n,i);return t.PdfTaskHelper.resolve(a)}removeEncryption(e){this.logger.debug(T,C,"removeEncryption",e);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDF_RemoveEncryption(o.docPtr);return t.PdfTaskHelper.resolve(n)}unlockOwnerPermissions(e,o){this.logger.debug(T,C,"unlockOwnerPermissions",e.id);const n=this.cache.getContext(e.id);if(!n)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.pdfiumModule.EPDF_UnlockOwnerPermissions(n.docPtr,o);return t.PdfTaskHelper.resolve(i)}isEncrypted(e){this.logger.debug(T,C,"isEncrypted",e.id);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDF_IsEncrypted(o.docPtr);return t.PdfTaskHelper.resolve(n)}isOwnerUnlocked(e){this.logger.debug(T,C,"isOwnerUnlocked",e.id);const o=this.cache.getContext(e.id);if(!o)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.pdfiumModule.EPDF_IsOwnerUnlocked(o.docPtr);return t.PdfTaskHelper.resolve(n)}saveAsCopy(e){this.logger.debug(T,C,"saveAsCopy",e),this.logger.perf(T,C,"SaveAsCopy","Begin",e.id);const o=this.cache.getContext(e.id);if(!o)return this.logger.perf(T,C,"SaveAsCopy","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const n=this.saveDocument(o.docPtr);return this.logger.perf(T,C,"SaveAsCopy","End",e.id),t.PdfTaskHelper.resolve(n)}closeDocument(e){this.logger.debug(T,C,"closeDocument",e),this.logger.perf(T,C,"CloseDocument","Begin",e.id);const o=this.cache.getContext(e.id);return o?(o.dispose(),this.logger.perf(T,C,"CloseDocument","End",e.id),t.PdfTaskHelper.resolve(!0)):t.PdfTaskHelper.resolve(!0)}closeAllDocuments(){return this.logger.debug(T,C,"closeAllDocuments"),this.logger.perf(T,C,"CloseAllDocuments","Begin"),this.cache.closeAllDocuments(),this.logger.perf(T,C,"CloseAllDocuments","End"),t.PdfTaskHelper.resolve(!0)}addTextContent(e,o,n,i){return!!this.setAnnotationIcon(n,i.icon||t.PdfAnnotationIcon.Comment)&&(!(i.state&&!this.setAnnotString(n,"State",i.state))&&(!(i.stateModel&&!this.setAnnotString(n,"StateModel",i.stateModel))&&(!(!i.flags&&!this.setAnnotationFlags(n,["print","noZoom","noRotate"]))&&this.applyBaseAnnotationProperties(o,n,i))))}addFreeTextContent(e,o,n,i){if(!this.setBorderStyle(n,t.PdfAnnotationBorderStyle.SOLID,0))return!1;if(!this.setAnnotationOpacity(n,i.opacity??1))return!1;if(!this.setAnnotationTextAlignment(n,i.textAlign))return!1;if(!this.setAnnotationVerticalAlignment(n,i.verticalAlign))return!1;if(!this.setAnnotationDefaultAppearance(n,i.fontFamily,i.fontSize,i.fontColor))return!1;if(i.intent&&!this.setAnnotIntent(n,i.intent))return!1;const r=i.color??i.backgroundColor;if(r&&"transparent"!==r){if(!this.setAnnotationColor(n,r??"#FFFFFF",t.PdfAnnotationColorType.Color))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,t.PdfAnnotationColorType.Color))return!1;return this.applyBaseAnnotationProperties(o,n,i)}addInkStroke(e,o,n,i){if(!this.setBorderStyle(n,t.PdfAnnotationBorderStyle.SOLID,i.strokeWidth))return!1;if(!this.setInkList(e,n,i.inkList))return!1;if(!this.setAnnotationOpacity(n,i.opacity??1))return!1;const r=i.strokeColor??i.color??"#FFFF00";return!!this.setAnnotationColor(n,r,t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(o,n,i)}addLineContent(e,o,n,i){var r,a;if(!this.setLinePoints(e,n,i.linePoints.start,i.linePoints.end))return!1;if(!this.setLineEndings(n,(null==(r=i.lineEndings)?void 0:r.start)??t.PdfAnnotationLineEnding.None,(null==(a=i.lineEndings)?void 0:a.end)??t.PdfAnnotationLineEnding.None))return!1;if(!this.setBorderStyle(n,i.strokeStyle,i.strokeWidth))return!1;if(!this.setBorderDashPattern(n,i.strokeDashArray??[]))return!1;if(i.intent&&!this.setAnnotIntent(n,i.intent))return!1;if(i.color&&"transparent"!==i.color){if(!this.setAnnotationColor(n,i.color??"#FFFF00",t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,t.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(n,i.opacity??1)&&(!!this.setAnnotationColor(n,i.strokeColor??"#FFFF00",t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(o,n,i))}addPolyContent(e,o,n,i){var r,a;if(i.type===t.PdfAnnotationSubtype.POLYLINE&&!this.setLineEndings(n,(null==(r=i.lineEndings)?void 0:r.start)??t.PdfAnnotationLineEnding.None,(null==(a=i.lineEndings)?void 0:a.end)??t.PdfAnnotationLineEnding.None))return!1;if(!this.setPdfAnnoVertices(e,n,i.vertices))return!1;if(!this.setBorderStyle(n,i.strokeStyle,i.strokeWidth))return!1;if(!this.setBorderDashPattern(n,i.strokeDashArray??[]))return!1;if(i.intent&&!this.setAnnotIntent(n,i.intent))return!1;if(i.color&&"transparent"!==i.color){if(!this.setAnnotationColor(n,i.color??"#FFFF00",t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,t.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(n,i.opacity??1)&&(!!this.setAnnotationColor(n,i.strokeColor??"#FFFF00",t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(o,n,i))}addLinkContent(e,o,n,i){const r=i.strokeStyle??t.PdfAnnotationBorderStyle.UNDERLINE,a=i.strokeWidth??2;return!!this.setBorderStyle(n,r,a)&&(!(i.strokeDashArray&&!this.setBorderDashPattern(n,i.strokeDashArray))&&(!(i.strokeColor&&!this.setAnnotationColor(n,i.strokeColor,t.PdfAnnotationColorType.Color))&&(!(i.target&&!this.applyLinkTarget(e,n,i.target))&&this.applyBaseAnnotationProperties(o,n,i))))}addShapeContent(e,o,n,i){if(!this.setBorderStyle(n,i.strokeStyle,i.strokeWidth))return!1;if(!this.setBorderDashPattern(n,i.strokeDashArray??[]))return!1;if(i.color&&"transparent"!==i.color){if(!this.setAnnotationColor(n,i.color??"#FFFF00",t.PdfAnnotationColorType.InteriorColor))return!1}else if(!this.pdfiumModule.EPDFAnnot_ClearColor(n,t.PdfAnnotationColorType.InteriorColor))return!1;return!!this.setAnnotationOpacity(n,i.opacity??1)&&(!!this.setAnnotationColor(n,i.strokeColor??"#FFFF00",t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(o,n,i))}addTextMarkupContent(e,o,n,i){if(!this.syncQuadPointsAnno(e,n,i.segmentRects))return!1;if(!this.setAnnotationOpacity(n,i.opacity??1))return!1;const r=i.strokeColor??i.color??"#FFFF00";return!!this.setAnnotationColor(n,r,t.PdfAnnotationColorType.Color)&&this.applyBaseAnnotationProperties(o,n,i)}addStampContent(e,o,n,i,r,a){if(r.icon&&!this.setAnnotationIcon(i,r.icon))return!1;if(r.subject&&!this.setAnnotString(i,"Subj",r.subject))return!1;if(a){for(let e=this.pdfiumModule.FPDFAnnot_GetObjectCount(i)-1;e>=0;e--)this.pdfiumModule.FPDFAnnot_RemoveObject(i,e);if(!this.addImageObject(e,o,n,i,r.rect,a))return!1}return!!this.pdfiumModule.EPDFAnnot_UpdateAppearanceToRect(i,t.PdfStampFit.Cover)&&this.applyBaseAnnotationProperties(n,i,r)}addImageObject(e,t,o,n,i,r){const a=r.width*r.height,s=this.memoryManager.malloc(4*a);if(!s)return!1;for(let c=0;c<a;c++){const e=r.data[4*c],t=r.data[4*c+1],o=r.data[4*c+2],n=r.data[4*c+3];this.pdfiumModule.pdfium.setValue(s+4*c,o,"i8"),this.pdfiumModule.pdfium.setValue(s+4*c+1,t,"i8"),this.pdfiumModule.pdfium.setValue(s+4*c+2,e,"i8"),this.pdfiumModule.pdfium.setValue(s+4*c+3,n,"i8")}const d=this.pdfiumModule.FPDFBitmap_CreateEx(r.width,r.height,4,s,0);if(!d)return this.memoryManager.free(s),!1;const l=this.pdfiumModule.FPDFPageObj_NewImageObj(e);if(!l)return this.pdfiumModule.FPDFBitmap_Destroy(d),this.memoryManager.free(s),!1;if(!this.pdfiumModule.FPDFImageObj_SetBitmap(o,0,l,d))return this.pdfiumModule.FPDFBitmap_Destroy(d),this.pdfiumModule.FPDFPageObj_Destroy(l),this.memoryManager.free(s),!1;const u=this.memoryManager.malloc(24);if(this.pdfiumModule.pdfium.setValue(u,r.width,"float"),this.pdfiumModule.pdfium.setValue(u+4,0,"float"),this.pdfiumModule.pdfium.setValue(u+8,0,"float"),this.pdfiumModule.pdfium.setValue(u+12,r.height,"float"),this.pdfiumModule.pdfium.setValue(u+16,0,"float"),this.pdfiumModule.pdfium.setValue(u+20,0,"float"),!this.pdfiumModule.FPDFPageObj_SetMatrix(l,u))return this.memoryManager.free(u),this.pdfiumModule.FPDFBitmap_Destroy(d),this.pdfiumModule.FPDFPageObj_Destroy(l),this.memoryManager.free(s),!1;this.memoryManager.free(u);const h=this.convertDevicePointToPagePoint(t,{x:i.origin.x,y:i.origin.y+r.height});return this.pdfiumModule.FPDFPageObj_Transform(l,1,0,0,1,h.x,h.y),this.pdfiumModule.FPDFAnnot_AppendObject(n,l)?(this.pdfiumModule.FPDFBitmap_Destroy(d),this.memoryManager.free(s),!0):(this.pdfiumModule.FPDFBitmap_Destroy(d),this.pdfiumModule.FPDFPageObj_Destroy(l),this.memoryManager.free(s),!1)}saveDocument(e){const t=this.pdfiumModule.PDFiumExt_OpenFileWriter();this.pdfiumModule.PDFiumExt_SaveAsCopy(e,t);const o=this.pdfiumModule.PDFiumExt_GetFileWriterSize(t),n=this.memoryManager.malloc(o);this.pdfiumModule.PDFiumExt_GetFileWriterData(t,n,o);const i=new ArrayBuffer(o),r=new DataView(i);for(let a=0;a<o;a++)r.setInt8(a,this.pdfiumModule.pdfium.getValue(n+a,"i8"));return this.memoryManager.free(n),this.pdfiumModule.PDFiumExt_CloseFileWriter(t),i}readCatalogLanguage(e){const t=this.pdfiumModule.EPDFCatalog_GetLanguage(e,0,0)>>>0;return 0===t?null:2===t?"":i(this.pdfiumModule.pdfium,(t,o)=>this.pdfiumModule.EPDFCatalog_GetLanguage(e,t,o),this.pdfiumModule.pdfium.UTF16ToString,t)}readMetaText(e,t){if(!!!this.pdfiumModule.EPDF_HasMetaText(e,t))return null;const o=this.pdfiumModule.FPDF_GetMetaText(e,t,0,0);return 2===o?"":i(this.pdfiumModule.pdfium,(o,n)=>this.pdfiumModule.FPDF_GetMetaText(e,t,o,n),this.pdfiumModule.pdfium.UTF16ToString,o)}setMetaText(e,t,o){if(null==o||0===o.length){return!!this.pdfiumModule.EPDF_SetMetaText(e,t,0)}const n=2*(o.length+1),i=this.memoryManager.malloc(n);try{this.pdfiumModule.pdfium.stringToUTF16(o,i,n);return!!this.pdfiumModule.EPDF_SetMetaText(e,t,i)}finally{this.memoryManager.free(i)}}getMetaTrapped(e){const o=Number(this.pdfiumModule.EPDF_GetMetaTrapped(e));switch(o){case t.PdfTrappedStatus.NotSet:case t.PdfTrappedStatus.True:case t.PdfTrappedStatus.False:case t.PdfTrappedStatus.Unknown:return o;default:return t.PdfTrappedStatus.Unknown}}setMetaTrapped(e,o){const n=null==o||void 0===o?t.PdfTrappedStatus.NotSet:o;return!(n!==t.PdfTrappedStatus.NotSet&&n!==t.PdfTrappedStatus.True&&n!==t.PdfTrappedStatus.False&&n!==t.PdfTrappedStatus.Unknown)&&!!this.pdfiumModule.EPDF_SetMetaTrapped(e,n)}getMetaKeyCount(e,t){return 0|Number(this.pdfiumModule.EPDF_GetMetaKeyCount(e,t))}getMetaKeyName(e,t,o){const n=this.pdfiumModule.EPDF_GetMetaKeyName(e,t,o,0,0);return n?i(this.pdfiumModule.pdfium,(n,i)=>this.pdfiumModule.EPDF_GetMetaKeyName(e,t,o,n,i),this.pdfiumModule.pdfium.UTF8ToString,n):null}readAllMeta(e,t=!0){const o=this.getMetaKeyCount(e,t),n={};for(let i=0;i<o;i++){const o=this.getMetaKeyName(e,i,t);o&&(n[o]=this.readMetaText(e,o))}return n}readPdfBookmarks(e,t=0){let o=this.pdfiumModule.FPDFBookmark_GetFirstChild(e,t);const n=[];for(;o;){const t=this.readPdfBookmark(e,o);n.push(t);o=this.pdfiumModule.FPDFBookmark_GetNextSibling(e,o)}return n}readPdfBookmark(e,t){const o=i(this.pdfiumModule.pdfium,(e,o)=>this.pdfiumModule.FPDFBookmark_GetTitle(t,e,o),this.pdfiumModule.pdfium.UTF16ToString),n=this.readPdfBookmarks(e,t);return{title:o,target:this.readPdfBookmarkTarget(e,()=>this.pdfiumModule.FPDFBookmark_GetAction(t),()=>this.pdfiumModule.FPDFBookmark_GetDest(e,t)),children:n}}readPageTextRects(e,t,o,n){const i=this.pdfiumModule.FPDFText_CountRects(n,0,-1),r=[];for(let a=0;a<i;a++){const t=this.memoryManager.malloc(8),i=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFText_GetRect(n,a,i,t,s,d)){this.memoryManager.free(i),this.memoryManager.free(t),this.memoryManager.free(s),this.memoryManager.free(d);continue}const l=this.pdfiumModule.pdfium.getValue(i,"double"),u=this.pdfiumModule.pdfium.getValue(t,"double"),h=this.pdfiumModule.pdfium.getValue(s,"double"),c=this.pdfiumModule.pdfium.getValue(d,"double");this.memoryManager.free(i),this.memoryManager.free(t),this.memoryManager.free(s),this.memoryManager.free(d);const g=this.memoryManager.malloc(4),f=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(o,0,0,e.size.width,e.size.height,0,l,u,g,f);const m=this.pdfiumModule.pdfium.getValue(g,"i32"),p=this.pdfiumModule.pdfium.getValue(f,"i32");this.memoryManager.free(g),this.memoryManager.free(f);const P={origin:{x:m,y:p},size:{width:Math.ceil(Math.abs(h-l)),height:Math.ceil(Math.abs(u-c))}},F=this.pdfiumModule.FPDFText_GetBoundedText(n,l,u,h,c,0,0),M=2*(F+1),y=this.memoryManager.malloc(M);this.pdfiumModule.FPDFText_GetBoundedText(n,l,u,h,c,y,F);const A=this.pdfiumModule.pdfium.UTF16ToString(y);this.memoryManager.free(y);const D=this.pdfiumModule.FPDFText_GetCharIndexAtPos(n,l,u,2,2);let T="",C=P.size.height;if(D>=0){C=this.pdfiumModule.FPDFText_GetFontSize(n,D);const e=this.pdfiumModule.FPDFText_GetFontInfo(n,D,0,0,0)+1,t=this.memoryManager.malloc(e),o=this.memoryManager.malloc(4);this.pdfiumModule.FPDFText_GetFontInfo(n,D,t,e,o),T=this.pdfiumModule.pdfium.UTF8ToString(t),this.memoryManager.free(t),this.memoryManager.free(o)}const E={content:A,rect:P,font:{family:T,size:C}};r.push(E)}return r}getPageGeometry(e,o){const n="getPageGeometry";this.logger.perf(T,C,n,"Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return this.logger.perf(T,C,n,"End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const r=i.acquirePage(o.index),a=r.getTextPage(),s=this.pdfiumModule.FPDFText_CountChars(a),d=[];for(let t=0;t<s;t++){const e=this.readGlyphInfo(o,r.pagePtr,a,t);d.push(e)}const l=this.buildRunsFromGlyphs(d,a);return r.release(),this.logger.perf(T,C,n,"End",e.id),t.PdfTaskHelper.resolve({runs:l})}buildRunsFromGlyphs(e,t){const o=[];let n=null,i=null,r=null;for(let a=0;a<e.length;a++){const s=e[a],d=this.pdfiumModule.FPDFText_GetTextObject(t,a);if(d!==i&&(i=d,n={rect:{x:s.origin.x,y:s.origin.y,width:s.size.width,height:s.size.height},charStart:a,glyphs:[]},r={minX:s.origin.x,minY:s.origin.y,maxX:s.origin.x+s.size.width,maxY:s.origin.y+s.size.height},o.push(n)),n.glyphs.push({x:s.origin.x,y:s.origin.y,width:s.size.width,height:s.size.height,flags:s.isEmpty?2:s.isSpace?1:0}),s.isEmpty)continue;const l=s.origin.x+s.size.width,u=s.origin.y+s.size.height;r.minX=Math.min(r.minX,s.origin.x),r.minY=Math.min(r.minY,s.origin.y),r.maxX=Math.max(r.maxX,l),r.maxY=Math.max(r.maxY,u),n.rect.x=r.minX,n.rect.y=r.minY,n.rect.width=r.maxX-r.minX,n.rect.height=r.maxY-r.minY}return o}readGlyphInfo(e,t,o,n){const i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),d=this.memoryManager.malloc(16);let l=0,u=0,h=0,c=0,g=!1;if(this.pdfiumModule.FPDFText_GetLooseCharBox(o,n,d)){const f=this.pdfiumModule.pdfium.getValue(d,"float"),m=this.pdfiumModule.pdfium.getValue(d+4,"float"),p=this.pdfiumModule.pdfium.getValue(d+8,"float"),P=this.pdfiumModule.pdfium.getValue(d+12,"float");if(f===p||m===P)return[d,i,r,a,s].forEach(e=>this.memoryManager.free(e)),{origin:{x:0,y:0},size:{width:0,height:0},isEmpty:!0};this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,f,m,i,r),this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,p,P,a,s);const F=this.pdfiumModule.pdfium.getValue(i,"i32"),M=this.pdfiumModule.pdfium.getValue(r,"i32"),y=this.pdfiumModule.pdfium.getValue(a,"i32"),A=this.pdfiumModule.pdfium.getValue(s,"i32");l=Math.min(F,y),u=Math.min(M,A),h=Math.max(1,Math.abs(y-F)),c=Math.max(1,Math.abs(A-M));g=32===this.pdfiumModule.FPDFText_GetUnicode(o,n)}return[d,i,r,a,s].forEach(e=>this.memoryManager.free(e)),{origin:{x:l,y:u},size:{width:h,height:c},...g&&{isSpace:g}}}getPageGlyphs(e,o){this.logger.debug(T,C,"getPageGlyphs",e,o),this.logger.perf(T,C,"getPageGlyphs","Begin",e.id);const n=this.cache.getContext(e.id);if(!n)return this.logger.perf(T,C,"getPageGlyphs","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=n.acquirePage(o.index),r=i.getTextPage(),a=this.pdfiumModule.FPDFText_CountChars(r),s=new Array(a);for(let t=0;t<a;t++){const e=this.readGlyphInfo(o,i.pagePtr,r,t);e.isEmpty||(s[t]={...e})}return i.release(),this.logger.perf(T,C,"getPageGlyphs","End",e.id),t.PdfTaskHelper.resolve(s)}readCharBox(e,t,o,n){const i=this.memoryManager.malloc(8),r=this.memoryManager.malloc(8),a=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8);let d=0,l=0,u=0,h=0;if(this.pdfiumModule.FPDFText_GetCharBox(o,n,r,s,a,i)){const o=this.pdfiumModule.pdfium.getValue(i,"double"),n=this.pdfiumModule.pdfium.getValue(r,"double"),c=this.pdfiumModule.pdfium.getValue(a,"double"),g=this.pdfiumModule.pdfium.getValue(s,"double"),f=this.memoryManager.malloc(4),m=this.memoryManager.malloc(4);this.pdfiumModule.FPDF_PageToDevice(t,0,0,e.size.width,e.size.height,0,n,o,f,m),d=this.pdfiumModule.pdfium.getValue(f,"i32"),l=this.pdfiumModule.pdfium.getValue(m,"i32"),this.memoryManager.free(f),this.memoryManager.free(m),u=Math.ceil(Math.abs(g-n)),h=Math.ceil(Math.abs(o-c))}return this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(a),this.memoryManager.free(s),{origin:{x:d,y:l},size:{width:u,height:h}}}readPageAnnotations(e,t){return e.borrowPage(t.index,o=>{const n=this.pdfiumModule.FPDFPage_GetAnnotCount(o.pagePtr),i=[];for(let r=0;r<n;r++)o.withAnnotation(r,n=>{const r=this.readPageAnnotation(e.docPtr,t,n,o);r&&i.push(r)});return i})}readPageAnnotationsRaw(e,t){const o=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e.docPtr,t.index);if(o<=0)return[];const n=[];for(let i=0;i<o;++i){const o=this.pdfiumModule.EPDFPage_GetAnnotRaw(e.docPtr,t.index,i);if(o)try{const i=this.readPageAnnotation(e.docPtr,t,o);i&&n.push(i)}finally{this.pdfiumModule.FPDFPage_CloseAnnot(o)}}return n}getPageAnnotationsRaw(e,o){this.logger.debug(T,C,"getPageAnnotationsRaw",e,o),this.logger.perf(T,C,"GetPageAnnotationsRaw","Begin",`${e.id}-${o.index}`);const n=this.cache.getContext(e.id);if(!n)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const i=this.readPageAnnotationsRaw(n,o);return this.logger.perf(T,C,"GetPageAnnotationsRaw","End",`${e.id}-${o.index}`),this.logger.debug(T,C,"getPageAnnotationsRaw",`${e.id}-${o.index}`,i),t.PdfTaskHelper.resolve(i)}readPageAnnotation(e,o,n,i){let r=this.getAnnotString(n,"NM");r&&t.isUuidV4(r)||(r=t.uuidV4(),this.setAnnotString(n,"NM",r));const a=this.pdfiumModule.FPDFAnnot_GetSubtype(n);let s;switch(a){case t.PdfAnnotationSubtype.TEXT:s=this.readPdfTextAnno(o,n,r);break;case t.PdfAnnotationSubtype.FREETEXT:s=this.readPdfFreeTextAnno(o,n,r);break;case t.PdfAnnotationSubtype.LINK:s=this.readPdfLinkAnno(o,e,n,r);break;case t.PdfAnnotationSubtype.WIDGET:if(i)return this.readPdfWidgetAnno(o,n,i.getFormHandle(),r);case t.PdfAnnotationSubtype.FILEATTACHMENT:s=this.readPdfFileAttachmentAnno(o,n,r);break;case t.PdfAnnotationSubtype.INK:s=this.readPdfInkAnno(o,n,r);break;case t.PdfAnnotationSubtype.POLYGON:s=this.readPdfPolygonAnno(o,n,r);break;case t.PdfAnnotationSubtype.POLYLINE:s=this.readPdfPolylineAnno(o,n,r);break;case t.PdfAnnotationSubtype.LINE:s=this.readPdfLineAnno(o,n,r);break;case t.PdfAnnotationSubtype.HIGHLIGHT:s=this.readPdfHighlightAnno(o,n,r);break;case t.PdfAnnotationSubtype.STAMP:s=this.readPdfStampAnno(o,n,r);break;case t.PdfAnnotationSubtype.SQUARE:s=this.readPdfSquareAnno(o,n,r);break;case t.PdfAnnotationSubtype.CIRCLE:s=this.readPdfCircleAnno(o,n,r);break;case t.PdfAnnotationSubtype.UNDERLINE:s=this.readPdfUnderlineAnno(o,n,r);break;case t.PdfAnnotationSubtype.SQUIGGLY:s=this.readPdfSquigglyAnno(o,n,r);break;case t.PdfAnnotationSubtype.STRIKEOUT:s=this.readPdfStrikeOutAnno(o,n,r);break;case t.PdfAnnotationSubtype.CARET:s=this.readPdfCaretAnno(o,n,r);break;default:s=this.readPdfAnno(o,a,n,r)}return s}readAnnotationColor(e,o=t.PdfAnnotationColorType.Color){const n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4);let a;return this.pdfiumModule.EPDFAnnot_GetColor(e,o,n,i,r)&&(a={red:255&this.pdfiumModule.pdfium.getValue(n,"i32"),green:255&this.pdfiumModule.pdfium.getValue(i,"i32"),blue:255&this.pdfiumModule.pdfium.getValue(r,"i32")}),this.memoryManager.free(n),this.memoryManager.free(i),this.memoryManager.free(r),a}getAnnotationColor(e,o=t.PdfAnnotationColorType.Color){const n=this.readAnnotationColor(e,o);return n?t.pdfColorToWebColor(n):void 0}setAnnotationColor(e,o,n=t.PdfAnnotationColorType.Color){const i=t.webColorToPdfColor(o);return this.pdfiumModule.EPDFAnnot_SetColor(e,n,255&i.red,255&i.green,255&i.blue)}getAnnotationOpacity(e){const o=this.memoryManager.malloc(4),n=this.pdfiumModule.EPDFAnnot_GetOpacity(e,o)?this.pdfiumModule.pdfium.getValue(o,"i32"):255;return this.memoryManager.free(o),t.pdfAlphaToWebOpacity(n)}setAnnotationOpacity(e,o){const n=t.webOpacityToPdfAlpha(o);return this.pdfiumModule.EPDFAnnot_SetOpacity(e,255&n)}getAnnotationTextAlignment(e){return this.pdfiumModule.EPDFAnnot_GetTextAlignment(e)}setAnnotationTextAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetTextAlignment(e,t)}getAnnotationVerticalAlignment(e){return this.pdfiumModule.EPDFAnnot_GetVerticalAlignment(e)}setAnnotationVerticalAlignment(e,t){return!!this.pdfiumModule.EPDFAnnot_SetVerticalAlignment(e,t)}getAnnotationDefaultAppearance(e){const o=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetDefaultAppearance(e,o,n,i,r,a))return void[o,n,i,r,a].forEach(e=>this.memoryManager.free(e));const s=this.pdfiumModule.pdfium,d=s.getValue(o,"i32"),l=s.getValue(n,"float"),u=255&s.getValue(i,"i32"),h=255&s.getValue(r,"i32"),c=255&s.getValue(a,"i32");return[o,n,i,r,a].forEach(e=>this.memoryManager.free(e)),{fontFamily:d,fontSize:l,fontColor:t.pdfColorToWebColor({red:u,green:h,blue:c})}}setAnnotationDefaultAppearance(e,o,n,i){const{red:r,green:a,blue:s}=t.webColorToPdfColor(i);return!!this.pdfiumModule.EPDFAnnot_SetDefaultAppearance(e,o,n,255&r,255&a,255&s)}getBorderStyle(e){const o=this.memoryManager.malloc(4);let n=0,i=t.PdfAnnotationBorderStyle.UNKNOWN,r=!1;return i=this.pdfiumModule.EPDFAnnot_GetBorderStyle(e,o),n=this.pdfiumModule.pdfium.getValue(o,"float"),r=i!==t.PdfAnnotationBorderStyle.UNKNOWN,this.memoryManager.free(o),{ok:r,style:i,width:n}}setBorderStyle(e,t,o){return this.pdfiumModule.EPDFAnnot_SetBorderStyle(e,t,o)}getAnnotationIcon(e){return this.pdfiumModule.EPDFAnnot_GetIcon(e)}setAnnotationIcon(e,t){return this.pdfiumModule.EPDFAnnot_SetIcon(e,t)}getReplyType(e){return this.pdfiumModule.EPDFAnnot_GetReplyType(e)}setReplyType(e,o){return this.pdfiumModule.EPDFAnnot_SetReplyType(e,o??t.PdfAnnotationReplyType.Unknown)}getBorderEffect(e){const t=this.memoryManager.malloc(4),o=!!this.pdfiumModule.EPDFAnnot_GetBorderEffect(e,t),n=o?this.pdfiumModule.pdfium.getValue(t,"float"):0;return this.memoryManager.free(t),{ok:o,intensity:n}}getRectangleDifferences(e){const t=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=!!this.pdfiumModule.EPDFAnnot_GetRectangleDifferences(e,t,o,n,i),a=this.pdfiumModule.pdfium,s=a.getValue(t,"float"),d=a.getValue(o,"float"),l=a.getValue(n,"float"),u=a.getValue(i,"float");return this.memoryManager.free(t),this.memoryManager.free(o),this.memoryManager.free(n),this.memoryManager.free(i),{ok:r,left:s,top:d,right:l,bottom:u}}getAnnotationDate(e,o){const n=this.getAnnotString(e,o);return n?t.pdfDateToDate(n):void 0}setAnnotationDate(e,o,n){const i=t.dateToPdfDate(n);return this.setAnnotString(e,o,i)}getAttachmentDate(e,o){const n=this.getAttachmentString(e,o);return n?t.pdfDateToDate(n):void 0}setAttachmentDate(e,o,n){const i=t.dateToPdfDate(n);return this.setAttachmentString(e,o,i)}getBorderDashPattern(e){const t=this.pdfiumModule.EPDFAnnot_GetBorderDashPatternCount(e);if(0===t)return{ok:!1,pattern:[]};const o=this.memoryManager.malloc(4*t),n=!!this.pdfiumModule.EPDFAnnot_GetBorderDashPattern(e,o,t),i=[];if(n){const e=this.pdfiumModule.pdfium;for(let n=0;n<t;n++)i.push(e.getValue(o+4*n,"float"))}return this.memoryManager.free(o),{ok:n,pattern:i}}setBorderDashPattern(e,t){if(!t||0===t.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const o=t.map(e=>Number.isFinite(e)&&e>0?e:0).filter(e=>e>0);if(0===o.length)return this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,0,0);const n=4*o.length,i=this.memoryManager.malloc(n);for(let a=0;a<o.length;a++)this.pdfiumModule.pdfium.setValue(i+4*a,o[a],"float");const r=!!this.pdfiumModule.EPDFAnnot_SetBorderDashPattern(e,i,o.length);return this.memoryManager.free(i),r}getLineEndings(e){const t=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4);if(!!!this.pdfiumModule.EPDFAnnot_GetLineEndings(e,t,o))return this.memoryManager.free(t),void this.memoryManager.free(o);const n=this.pdfiumModule.pdfium.getValue(t,"i32"),i=this.pdfiumModule.pdfium.getValue(o,"i32");return this.memoryManager.free(t),this.memoryManager.free(o),{start:n,end:i}}setLineEndings(e,t,o){return!!this.pdfiumModule.EPDFAnnot_SetLineEndings(e,t,o)}getLinePoints(e,t){const o=this.memoryManager.malloc(8),n=this.memoryManager.malloc(8);if(!this.pdfiumModule.FPDFAnnot_GetLine(t,o,n))return this.memoryManager.free(o),void this.memoryManager.free(n);const i=this.pdfiumModule.pdfium,r=i.getValue(o+0,"float"),a=i.getValue(o+4,"float"),s=i.getValue(n+0,"float"),d=i.getValue(n+4,"float");this.memoryManager.free(o),this.memoryManager.free(n);return{start:this.convertPagePointToDevicePoint(e,{x:r,y:a}),end:this.convertPagePointToDevicePoint(e,{x:s,y:d})}}setLinePoints(e,t,o,n){const i=this.convertDevicePointToPagePoint(e,o),r=this.convertDevicePointToPagePoint(e,n);if(!i||!r)return!1;const a=this.memoryManager.malloc(16),s=this.pdfiumModule.pdfium;s.setValue(a+0,i.x,"float"),s.setValue(a+4,i.y,"float"),s.setValue(a+8,r.x,"float"),s.setValue(a+12,r.y,"float");const d=this.pdfiumModule.EPDFAnnot_SetLine(t,a,a+8);return this.memoryManager.free(a),!!d}getQuadPointsAnno(e,o){const n=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(o);if(0===n)return[];const i=[];for(let t=0;t<n;t++){const n=this.memoryManager.malloc(32);if(this.pdfiumModule.FPDFAnnot_GetAttachmentPoints(o,t,n)){const t=[],o=[];for(let e=0;e<4;e++){const i=n+8*e;t.push(this.pdfiumModule.pdfium.getValue(i,"float")),o.push(this.pdfiumModule.pdfium.getValue(i+4,"float"))}const r=this.convertPagePointToDevicePoint(e,{x:t[0],y:o[0]}),a=this.convertPagePointToDevicePoint(e,{x:t[1],y:o[1]}),s=this.convertPagePointToDevicePoint(e,{x:t[2],y:o[2]}),d=this.convertPagePointToDevicePoint(e,{x:t[3],y:o[3]});i.push({p1:r,p2:a,p3:s,p4:d})}this.memoryManager.free(n)}return i.map(t.quadToRect)}syncQuadPointsAnno(e,o,n){const i=this.pdfiumModule.pdfium,r=this.pdfiumModule.FPDFAnnot_CountAttachmentPoints(o),a=this.memoryManager.malloc(32),s=o=>{const n=t.rectToQuad(o),r=this.convertDevicePointToPagePoint(e,n.p1),s=this.convertDevicePointToPagePoint(e,n.p2),d=this.convertDevicePointToPagePoint(e,n.p3),l=this.convertDevicePointToPagePoint(e,n.p4);i.setValue(a+0,r.x,"float"),i.setValue(a+4,r.y,"float"),i.setValue(a+8,s.x,"float"),i.setValue(a+12,s.y,"float"),i.setValue(a+16,l.x,"float"),i.setValue(a+20,l.y,"float"),i.setValue(a+24,d.x,"float"),i.setValue(a+28,d.y,"float")},d=Math.min(r,n.length);for(let t=0;t<d;t++)if(s(n[t]),!this.pdfiumModule.FPDFAnnot_SetAttachmentPoints(o,t,a))return this.memoryManager.free(a),!1;for(let t=r;t<n.length;t++)if(s(n[t]),!this.pdfiumModule.FPDFAnnot_AppendAttachmentPoints(o,a))return this.memoryManager.free(a),!1;return this.memoryManager.free(a),!0}redactTextInRects(e,o,n,i){const{recurseForms:r=!0,drawBlackBoxes:a=!1}=i??{};this.logger.debug("PDFiumEngine","Engine","redactTextInQuads",e.id,o.index,n.length);const s="RedactTextInQuads";this.logger.perf("PDFiumEngine","Engine",s,"Begin",`${e.id}-${o.index}`);const d=this.cache.getContext(e.id);if(!d)return this.logger.perf("PDFiumEngine","Engine",s,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const l=(n??[]).filter(e=>{var t,o,n,i;return e&&Number.isFinite(null==(t=e.origin)?void 0:t.x)&&Number.isFinite(null==(o=e.origin)?void 0:o.y)&&Number.isFinite(null==(n=e.size)?void 0:n.width)&&Number.isFinite(null==(i=e.size)?void 0:i.height)&&e.size.width>0&&e.size.height>0});if(0===l.length)return this.logger.perf("PDFiumEngine","Engine",s,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!1);const u=d.acquirePage(o.index),{ptr:h,count:c}=this.allocFSQuadsBufferFromRects(o,l);let g=!1;try{g=!!this.pdfiumModule.EPDFText_RedactInQuads(u.pagePtr,h,c,!!r,!!a)}finally{this.memoryManager.free(h)}return g&&(g=!!this.pdfiumModule.FPDFPage_GenerateContent(u.pagePtr)),u.disposeImmediate(),this.logger.perf("PDFiumEngine","Engine",s,"End",`${e.id}-${o.index}`),t.PdfTaskHelper.resolve(!!g)}allocFSQuadsBufferFromRects(e,o){const n=o.length,i=this.memoryManager.malloc(32*n),r=this.pdfiumModule.pdfium;for(let a=0;a<n;a++){const n=o[a],s=t.rectToQuad(n),d=this.convertDevicePointToPagePoint(e,s.p1),l=this.convertDevicePointToPagePoint(e,s.p2),u=this.convertDevicePointToPagePoint(e,s.p3),h=this.convertDevicePointToPagePoint(e,s.p4),c=i+32*a;r.setValue(c+0,d.x,"float"),r.setValue(c+4,d.y,"float"),r.setValue(c+8,l.x,"float"),r.setValue(c+12,l.y,"float"),r.setValue(c+16,h.x,"float"),r.setValue(c+20,h.y,"float"),r.setValue(c+24,u.x,"float"),r.setValue(c+28,u.y,"float")}return{ptr:i,count:n}}getInkList(e,t){const o=[],n=this.pdfiumModule.FPDFAnnot_GetInkListCount(t);if(n<=0)return o;const i=this.pdfiumModule.pdfium;for(let r=0;r<n;r++){const n=[],a=this.pdfiumModule.FPDFAnnot_GetInkListPath(t,r,0,0);if(a>0){const o=this.memoryManager.malloc(8*a);this.pdfiumModule.FPDFAnnot_GetInkListPath(t,r,o,a);for(let t=0;t<a;t++){const r=o+8*t,a=i.getValue(r+0,"float"),s=i.getValue(r+4,"float"),d=this.convertPagePointToDevicePoint(e,{x:a,y:s});n.push({x:d.x,y:d.y})}this.memoryManager.free(o)}o.push({points:n})}return o}setInkList(e,t,o){const n=this.pdfiumModule.pdfium;for(const i of o){const o=i.points.length;if(0===o)continue;const r=this.memoryManager.malloc(8*o);for(let t=0;t<o;t++){const o=i.points[t],a=this.convertDevicePointToPagePoint(e,o);n.setValue(r+8*t+0,a.x,"float"),n.setValue(r+8*t+4,a.y,"float")}const a=this.pdfiumModule.FPDFAnnot_AddInkStroke(t,r,o);if(this.memoryManager.free(r),-1===a)return!1}return!0}readPdfTextAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getAnnotString(o,"State"),s=this.getAnnotString(o,"StateModel"),d=this.getAnnotationColor(o),l=this.getAnnotationOpacity(o),u=this.getAnnotationIcon(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.TEXT,rect:r,color:d??"#FFFF00",opacity:l,state:a,stateModel:s,icon:u,...this.readBaseAnnotationProperties(o)}}readPdfFreeTextAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getAnnotString(o,"DS"),s=this.getAnnotationDefaultAppearance(o),d=this.getAnnotationColor(o),l=this.getAnnotationTextAlignment(o),u=this.getAnnotationVerticalAlignment(o),h=this.getAnnotationOpacity(o),c=this.getAnnotRichContent(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.FREETEXT,rect:r,fontFamily:(null==s?void 0:s.fontFamily)??t.PdfStandardFont.Unknown,fontSize:(null==s?void 0:s.fontSize)??12,fontColor:(null==s?void 0:s.fontColor)??"#000000",verticalAlign:u,color:d,backgroundColor:d,opacity:h,textAlign:l,defaultStyle:a,richContent:c,...this.readBaseAnnotationProperties(o)}}readPdfLinkAnno(e,o,n,i){const r=this.pdfiumModule.FPDFAnnot_GetLink(n);if(!r)return;const a=this.readPageAnnoRect(n),s=this.convertPageRectToDeviceRect(e,a),{style:d,width:l}=this.getBorderStyle(n),u=this.getAnnotationColor(n,t.PdfAnnotationColorType.Color);let h;if(d===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(n);e&&(h=t)}const c=this.readPdfLinkAnnoTarget(o,()=>this.pdfiumModule.FPDFLink_GetAction(r),()=>this.pdfiumModule.FPDFLink_GetDest(o,r));return{pageIndex:e.index,id:i,type:t.PdfAnnotationSubtype.LINK,rect:s,target:c,strokeColor:u,strokeWidth:l,strokeStyle:d,strokeDashArray:h,...this.readBaseAnnotationProperties(n)}}readPdfWidgetAnno(e,o,n,i){const r=this.readPageAnnoRect(o),a=this.convertPageRectToDeviceRect(e,r),s=this.readPdfWidgetAnnoField(n,o);return{pageIndex:e.index,id:i,type:t.PdfAnnotationSubtype.WIDGET,rect:a,field:s,...this.readBaseAnnotationProperties(o)}}readPdfFileAttachmentAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.FILEATTACHMENT,rect:r,...this.readBaseAnnotationProperties(o)}}readPdfInkAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getAnnotationColor(o)??"#FF0000",s=this.getAnnotationOpacity(o),{width:d}=this.getBorderStyle(o),l=this.getInkList(e,o),u=this.pdfiumModule.EPDFAnnot_GetBlendMode(o),h=this.getAnnotIntent(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.INK,rect:r,...h&&{intent:h},blendMode:u,strokeColor:a,color:a,opacity:s,strokeWidth:0===d?1:d,inkList:l,...this.readBaseAnnotationProperties(o)}}readPdfPolygonAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.readPdfAnnoVertices(e,o),s=this.getAnnotationColor(o),d=this.getAnnotationColor(o,t.PdfAnnotationColorType.InteriorColor),l=this.getAnnotationOpacity(o),{style:u,width:h}=this.getBorderStyle(o);let c;if(u===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(c=t)}if(a.length>1){const e=a[0],t=a[a.length-1];e.x===t.x&&e.y===t.y&&a.pop()}return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.POLYGON,rect:r,strokeColor:s??"#FF0000",color:d??"transparent",opacity:l,strokeWidth:0===h?1:h,strokeStyle:u,strokeDashArray:c,vertices:a,...this.readBaseAnnotationProperties(o)}}readPdfPolylineAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.readPdfAnnoVertices(e,o),s=this.getAnnotationColor(o),d=this.getAnnotationColor(o,t.PdfAnnotationColorType.InteriorColor),l=this.getAnnotationOpacity(o),{style:u,width:h}=this.getBorderStyle(o);let c;if(u===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(c=t)}const g=this.getLineEndings(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.POLYLINE,rect:r,strokeColor:s??"#FF0000",color:d??"transparent",opacity:l,strokeWidth:0===h?1:h,strokeStyle:u,strokeDashArray:c,lineEndings:g,vertices:a,...this.readBaseAnnotationProperties(o)}}readPdfLineAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getLinePoints(e,o),s=this.getLineEndings(o),d=this.getAnnotationColor(o),l=this.getAnnotationColor(o,t.PdfAnnotationColorType.InteriorColor),u=this.getAnnotationOpacity(o),{style:h,width:c}=this.getBorderStyle(o);let g;if(h===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(g=t)}return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.LINE,rect:r,strokeWidth:0===c?1:c,strokeStyle:h,strokeDashArray:g,strokeColor:d??"#FF0000",color:l??"transparent",opacity:u,linePoints:a||{start:{x:0,y:0},end:{x:0,y:0}},lineEndings:s||{start:t.PdfAnnotationLineEnding.None,end:t.PdfAnnotationLineEnding.None},...this.readBaseAnnotationProperties(o)}}readPdfHighlightAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getQuadPointsAnno(e,o),s=this.getAnnotationColor(o)??"#FFFF00",d=this.getAnnotationOpacity(o),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.HIGHLIGHT,rect:r,blendMode:l,segmentRects:a,strokeColor:s,color:s,opacity:d,...this.readBaseAnnotationProperties(o)}}readPdfUnderlineAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getQuadPointsAnno(e,o),s=this.getAnnotationColor(o)??"#FF0000",d=this.getAnnotationOpacity(o),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.UNDERLINE,rect:r,blendMode:l,segmentRects:a,strokeColor:s,color:s,opacity:d,...this.readBaseAnnotationProperties(o)}}readPdfStrikeOutAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getQuadPointsAnno(e,o),s=this.getAnnotationColor(o)??"#FF0000",d=this.getAnnotationOpacity(o),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.STRIKEOUT,rect:r,blendMode:l,segmentRects:a,strokeColor:s,color:s,opacity:d,...this.readBaseAnnotationProperties(o)}}readPdfSquigglyAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getQuadPointsAnno(e,o),s=this.getAnnotationColor(o)??"#FF0000",d=this.getAnnotationOpacity(o),l=this.pdfiumModule.EPDFAnnot_GetBlendMode(o);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.SQUIGGLY,rect:r,blendMode:l,segmentRects:a,strokeColor:s,color:s,opacity:d,...this.readBaseAnnotationProperties(o)}}readPdfCaretAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.CARET,rect:r,...this.readBaseAnnotationProperties(o)}}readPdfStampAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i);return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.STAMP,rect:r,...this.readBaseAnnotationProperties(o)}}readPdfPageObject(e){switch(this.pdfiumModule.FPDFPageObj_GetType(e)){case t.PdfPageObjectType.PATH:return this.readPathObject(e);case t.PdfPageObjectType.IMAGE:return this.readImageObject(e);case t.PdfPageObjectType.FORM:return this.readFormObject(e)}}readPathObject(e){const o=this.pdfiumModule.FPDFPath_CountSegments(e),n=this.memoryManager.malloc(4),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPageObj_GetBounds(e,n,i,r,a);const s={left:this.pdfiumModule.pdfium.getValue(n,"float"),bottom:this.pdfiumModule.pdfium.getValue(i,"float"),right:this.pdfiumModule.pdfium.getValue(r,"float"),top:this.pdfiumModule.pdfium.getValue(a,"float")};this.memoryManager.free(n),this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(a);const d=[];for(let t=0;t<o;t++){const o=this.readPdfSegment(e,t);d.push(o)}const l=this.readPdfPageObjectTransformMatrix(e);return{type:t.PdfPageObjectType.PATH,bounds:s,segments:d,matrix:l}}readPdfSegment(e,t){const o=this.pdfiumModule.FPDFPath_GetPathSegment(e,t),n=this.pdfiumModule.FPDFPathSegment_GetType(o),i=this.pdfiumModule.FPDFPathSegment_GetClose(o),r=this.memoryManager.malloc(4),a=this.memoryManager.malloc(4);this.pdfiumModule.FPDFPathSegment_GetPoint(o,r,a);const s=this.pdfiumModule.pdfium.getValue(r,"float"),d=this.pdfiumModule.pdfium.getValue(a,"float");return this.memoryManager.free(r),this.memoryManager.free(a),{type:n,point:{x:s,y:d},isClosed:i}}readImageObject(e){const o=this.pdfiumModule.FPDFImageObj_GetBitmap(e),n=this.pdfiumModule.FPDFBitmap_GetBuffer(o),i=this.pdfiumModule.FPDFBitmap_GetWidth(o),r=this.pdfiumModule.FPDFBitmap_GetHeight(o),a=this.pdfiumModule.FPDFBitmap_GetFormat(o),s=i*r,d=new Uint8ClampedArray(4*s);for(let t=0;t<s;t++)if(2===a){const e=this.pdfiumModule.pdfium.getValue(n+3*t,"i8"),o=this.pdfiumModule.pdfium.getValue(n+3*t+1,"i8"),i=this.pdfiumModule.pdfium.getValue(n+3*t+2,"i8");d[4*t]=i,d[4*t+1]=o,d[4*t+2]=e,d[4*t+3]=100}const l={data:d,width:i,height:r},u=this.readPdfPageObjectTransformMatrix(e);return{type:t.PdfPageObjectType.IMAGE,imageData:l,matrix:u}}readFormObject(e){const o=this.pdfiumModule.FPDFFormObj_CountObjects(e),n=[];for(let t=0;t<o;t++){const o=this.pdfiumModule.FPDFFormObj_GetObject(e,t),i=this.readPdfPageObject(o);i&&n.push(i)}const i=this.readPdfPageObjectTransformMatrix(e);return{type:t.PdfPageObjectType.FORM,objects:n,matrix:i}}readPdfPageObjectTransformMatrix(e){const t=this.memoryManager.malloc(24);if(this.pdfiumModule.FPDFPageObj_GetMatrix(e,t)){const e=this.pdfiumModule.pdfium.getValue(t,"float"),o=this.pdfiumModule.pdfium.getValue(t+4,"float"),n=this.pdfiumModule.pdfium.getValue(t+8,"float"),i=this.pdfiumModule.pdfium.getValue(t+12,"float"),r=this.pdfiumModule.pdfium.getValue(t+16,"float"),a=this.pdfiumModule.pdfium.getValue(t+20,"float");return this.memoryManager.free(t),{a:e,b:o,c:n,d:i,e:r,f:a}}return this.memoryManager.free(t),{a:1,b:0,c:0,d:1,e:0,f:0}}readStampAnnotationContents(e){const t=[],o=this.pdfiumModule.FPDFAnnot_GetObjectCount(e);for(let n=0;n<o;n++){const o=this.pdfiumModule.FPDFAnnot_GetObject(e,n),i=this.readPdfPageObject(o);i&&t.push(i)}return t}getStrokeWidth(e){const t=this.memoryManager.malloc(4),o=this.memoryManager.malloc(4),n=this.memoryManager.malloc(4),i=this.pdfiumModule.FPDFAnnot_GetBorder(e,t,o,n)?this.pdfiumModule.pdfium.getValue(n,"float"):1;return this.memoryManager.free(t),this.memoryManager.free(o),this.memoryManager.free(n),i}getAnnotationFlags(e){const o=this.pdfiumModule.FPDFAnnot_GetFlags(e);return t.flagsToNames(o)}setAnnotationFlags(e,o){const n=t.namesToFlags(o);return this.pdfiumModule.FPDFAnnot_SetFlags(e,n)}readPdfCircleAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getAnnotationColor(o,t.PdfAnnotationColorType.InteriorColor),s=this.getAnnotationColor(o),d=this.getAnnotationOpacity(o),{style:l,width:u}=this.getBorderStyle(o);let h;if(l===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(h=t)}return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.CIRCLE,rect:r,color:a??"transparent",opacity:d,strokeWidth:u,strokeColor:s??"#FF0000",strokeStyle:l,...void 0!==h&&{strokeDashArray:h},...this.readBaseAnnotationProperties(o)}}readPdfSquareAnno(e,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i),a=this.getAnnotationColor(o,t.PdfAnnotationColorType.InteriorColor),s=this.getAnnotationColor(o),d=this.getAnnotationOpacity(o),{style:l,width:u}=this.getBorderStyle(o);let h;if(l===t.PdfAnnotationBorderStyle.DASHED){const{ok:e,pattern:t}=this.getBorderDashPattern(o);e&&(h=t)}return{pageIndex:e.index,id:n,type:t.PdfAnnotationSubtype.SQUARE,rect:r,color:a??"transparent",opacity:d,strokeColor:s??"#FF0000",strokeWidth:u,strokeStyle:l,...void 0!==h&&{strokeDashArray:h},...this.readBaseAnnotationProperties(o)}}readPdfAnno(e,t,o,n){const i=this.readPageAnnoRect(o),r=this.convertPageRectToDeviceRect(e,i);return{pageIndex:e.index,id:n,type:t,rect:r,...this.readBaseAnnotationProperties(o)}}getInReplyToId(e){const t=this.pdfiumModule.FPDFAnnot_GetLinkedAnnot(e,"IRT");if(t)return this.getAnnotString(t,"NM")}setInReplyToId(e,t,o){if(!o)return this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",0);const n=this.getAnnotationByName(e,o);return!!n&&this.pdfiumModule.EPDFAnnot_SetLinkedAnnot(t,"IRT",n)}applyBaseAnnotationProperties(e,t,o){return!!this.setAnnotString(t,"T",o.author||"")&&(!!this.setAnnotString(t,"Contents",o.contents??"")&&(!(o.modified&&!this.setAnnotationDate(t,"M",o.modified))&&(!(o.created&&!this.setAnnotationDate(t,"CreationDate",o.created))&&(!(o.flags&&!this.setAnnotationFlags(t,o.flags))&&(!(o.custom&&!this.setAnnotCustom(t,o.custom))&&(!!this.setInReplyToId(e,t,o.inReplyToId)&&!!this.setReplyType(t,o.replyType)))))))}readBaseAnnotationProperties(e){const o=this.getAnnotString(e,"T"),n=this.getAnnotString(e,"Contents")||"",i=this.getAnnotationDate(e,"M"),r=this.getAnnotationDate(e,"CreationDate"),a=this.getAnnotationFlags(e),s=this.getAnnotCustom(e),d=this.getInReplyToId(e),l=this.getReplyType(e);return{author:o,contents:n,modified:i,created:r,flags:a,custom:s,...d&&{inReplyToId:d},...l&&l!==t.PdfAnnotationReplyType.Reply&&{replyType:l}}}getAnnotString(e,t){const o=this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,0,0);if(0===o)return;const n=2*(o+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetStringValue(e,t,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r||void 0}getAttachmentString(e,t){const o=this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,0,0);if(0===o)return;const n=2*(o+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAttachment_GetStringValue(e,t,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r||void 0}getAttachmentNumber(e,t){const o=this.memoryManager.malloc(4);try{if(!this.pdfiumModule.EPDFAttachment_GetIntegerValue(e,t,o))return;return this.pdfiumModule.pdfium.getValue(o,"i32")>>>0}finally{this.memoryManager.free(o)}}getAnnotCustom(e){const t=this.getAnnotString(e,"EPDFCustom");if(t)try{return JSON.parse(t)}catch(o){return console.warn("Failed to parse annotation custom data as JSON:",o),void console.warn("Invalid JSON string:",t)}}setAnnotCustom(e,t){if(null==t)return this.setAnnotString(e,"EPDFCustom","");try{const o=JSON.stringify(t);return this.setAnnotString(e,"EPDFCustom",o)}catch(o){return console.warn("Failed to stringify annotation custom data as JSON:",o),console.warn("Invalid data object:",t),!1}}getAnnotIntent(e){const t=this.pdfiumModule.EPDFAnnot_GetIntent(e,0,0);if(0===t)return;const o=2*(t+1),n=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetIntent(e,n,o);const i=this.pdfiumModule.pdfium.UTF16ToString(n);return this.memoryManager.free(n),i&&"undefined"!==i?i:void 0}setAnnotIntent(e,t){return this.pdfiumModule.EPDFAnnot_SetIntent(e,t)}getAnnotRichContent(e){const t=this.pdfiumModule.EPDFAnnot_GetRichContent(e,0,0);if(0===t)return;const o=2*(t+1),n=this.memoryManager.malloc(o);this.pdfiumModule.EPDFAnnot_GetRichContent(e,n,o);const i=this.pdfiumModule.pdfium.UTF16ToString(n);return this.memoryManager.free(n),i||void 0}getAnnotationByName(e,t){return this.withWString(t,t=>this.pdfiumModule.EPDFPage_GetAnnotByName(e,t))}removeAnnotationByName(e,t){return this.withWString(t,t=>this.pdfiumModule.EPDFPage_RemoveAnnotByName(e,t))}setAnnotString(e,t,o){return this.withWString(o,o=>this.pdfiumModule.FPDFAnnot_SetStringValue(e,t,o))}setAttachmentString(e,t,o){return this.withWString(o,o=>this.pdfiumModule.FPDFAttachment_SetStringValue(e,t,o))}readPdfAnnoVertices(e,t){const o=[],n=this.pdfiumModule.FPDFAnnot_GetVertices(t,0,0),i=this.memoryManager.malloc(8*n);this.pdfiumModule.FPDFAnnot_GetVertices(t,i,n);for(let r=0;r<n;r++){const t=this.pdfiumModule.pdfium.getValue(i+8*r,"float"),n=this.pdfiumModule.pdfium.getValue(i+8*r+4,"float"),{x:a,y:s}=this.convertPagePointToDevicePoint(e,{x:t,y:n}),d=o[o.length-1];d&&d.x===a&&d.y===s||o.push({x:a,y:s})}return this.memoryManager.free(i),o}setPdfAnnoVertices(e,t,o){const n=this.pdfiumModule.pdfium,i=this.memoryManager.malloc(8*o.length);o.forEach((t,o)=>{const r=this.convertDevicePointToPagePoint(e,t);n.setValue(i+8*o+0,r.x,"float"),n.setValue(i+8*o+4,r.y,"float")});const r=this.pdfiumModule.EPDFAnnot_SetVertices(t,i,o.length);return this.memoryManager.free(i),r}readPdfBookmarkTarget(e,t,o){const n=t();if(n){return{type:"action",action:this.readPdfAction(e,n)}}{const t=o();if(t){return{type:"destination",destination:this.readPdfDestination(e,t)}}}}readPdfWidgetAnnoField(e,o){const n=this.pdfiumModule.FPDFAnnot_GetFormFieldFlags(e,o),r=this.pdfiumModule.FPDFAnnot_GetFormFieldType(e,o),a=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAnnot_GetFormFieldName(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString),s=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAnnot_GetFormFieldAlternateName(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString),d=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAnnot_GetFormFieldValue(e,o,t,n),this.pdfiumModule.pdfium.UTF16ToString),l=[];if(r===t.PDF_FORM_FIELD_TYPE.COMBOBOX||r===t.PDF_FORM_FIELD_TYPE.LISTBOX){const t=this.pdfiumModule.FPDFAnnot_GetOptionCount(e,o);for(let n=0;n<t;n++){const t=i(this.pdfiumModule.pdfium,(t,i)=>this.pdfiumModule.FPDFAnnot_GetOptionLabel(e,o,n,t,i),this.pdfiumModule.pdfium.UTF16ToString),r=this.pdfiumModule.FPDFAnnot_IsOptionSelected(e,o,n);l.push({label:t,isSelected:r})}}let u=!1;return r!==t.PDF_FORM_FIELD_TYPE.CHECKBOX&&r!==t.PDF_FORM_FIELD_TYPE.RADIOBUTTON||(u=this.pdfiumModule.FPDFAnnot_IsChecked(e,o)),{flag:n,type:r,name:a,alternateName:s,value:d,isChecked:u,options:l}}renderPageAnnotationRaw(e,o,n,i){const{scaleFactor:r=1,rotation:a=t.Rotation.Degree0,dpr:s=1,mode:d=t.AppearanceMode.Normal}=i??{};this.logger.debug(T,C,"renderPageAnnotation",e,o,n,i),this.logger.perf(T,C,"RenderPageAnnotation","Begin",`${e.id}-${o.index}-${n.id}`);const l=new t.Task,u=this.cache.getContext(e.id);if(!u)return this.logger.perf(T,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const h=u.acquirePage(o.index),c=this.getAnnotationByName(h.pagePtr,n.id);if(!c)return this.logger.perf(T,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),h.release(),t.PdfTaskHelper.reject({code:t.PdfErrorCode.NotFound,message:"annotation not found"});const g=Math.max(.01,r*s),f=t.toIntRect(n.rect),m=t.toIntRect(t.transformRect(o.size,f,a,g)),p=Math.max(1,m.size.width),P=Math.max(1,m.size.height),F=4*p,M=F*P,y=this.memoryManager.malloc(M),A=this.pdfiumModule.FPDFBitmap_CreateEx(p,P,4,y,F);this.pdfiumModule.FPDFBitmap_FillRect(A,0,0,p,P,0);const D=t.buildUserToDeviceMatrix(f,a,p,P),E=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,E,6).set([D.a,D.b,D.c,D.d,D.e,D.f]);let x=!1;try{x=!!this.pdfiumModule.EPDF_RenderAnnotBitmap(A,h.pagePtr,c,d,E,16)}finally{this.memoryManager.free(E),this.pdfiumModule.FPDFBitmap_Destroy(A),this.pdfiumModule.FPDFPage_CloseAnnot(c),h.release()}if(!x)return this.memoryManager.free(y),this.logger.perf(T,C,"RenderPageAnnotation","End",`${e.id}-${o.index}-${n.id}`),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:"EPDF_RenderAnnotBitmap failed"});const k=this.pdfiumModule.pdfium.HEAPU8.subarray(y,y+M),S={data:new Uint8ClampedArray(k),width:p,height:P};return l.resolve(S),this.memoryManager.free(y),l}renderRectEncoded(e,o,n,i){const r=new t.Task,a=(null==i?void 0:i.rotation)??t.Rotation.Degree0,s=this.cache.getContext(e.id);if(!s)return t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"document does not open"});const l=Math.max(.01,(null==i?void 0:i.scaleFactor)??1)*Math.max(1,(null==i?void 0:i.dpr)??1),u=n.size.width,h=n.size.height,c=!(1&~a),g=Math.max(1,Math.round((c?h:u)*l)),f=Math.max(1,Math.round((c?u:h)*l)),m=4*g,p=m*f,P=s.acquirePage(o.index),F=(null==i?void 0:i.withForms)??!1?P.getFormHandle():void 0,M=this.memoryManager.malloc(p),y=this.pdfiumModule.FPDFBitmap_CreateEx(g,f,4,M,m);this.pdfiumModule.FPDFBitmap_FillRect(y,0,0,g,f,4294967295);const A=t.buildUserToDeviceMatrix(n,a,g,f),D=this.memoryManager.malloc(24);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,D,6).set([A.a,A.b,A.c,A.d,A.e,A.f]);const E=this.memoryManager.malloc(16);new Float32Array(this.pdfiumModule.pdfium.HEAPF32.buffer,E,4).set([0,0,g,f]);let x=16;(null==i?void 0:i.withAnnotations)&&(x|=1);try{if(this.pdfiumModule.FPDF_RenderPageBitmapWithMatrix(y,P.pagePtr,D,E,x),void 0!==F){const e=d(A,n,o.size,a),{startX:t,startY:i,formsWidth:r,formsHeight:s,scaleX:l,scaleY:u}=e;this.pdfiumModule.FPDF_FFLDraw(F,y,P.pagePtr,t,i,r,s,a,x)}}finally{P.release(),this.memoryManager.free(D),this.memoryManager.free(E)}this.logger.perf(T,C,"RenderRectEncodedData","Begin",`${e.id}-${o.index}`);const k=this.pdfiumModule.pdfium.HEAPU8.subarray(M,M+p);this.logger.perf(T,C,"RenderRectEncodedData","End",`${e.id}-${o.index}`),this.logger.perf(T,C,"RenderRectEncodedImageData","Begin",`${e.id}-${o.index}`);const S={data:new Uint8ClampedArray(k),width:g,height:f};return this.logger.perf(T,C,"RenderRectEncodedImageData","End",`${e.id}-${o.index}`),r.resolve(S),this.pdfiumModule.FPDFBitmap_Destroy(y),this.memoryManager.free(M),r}readPdfLinkAnnoTarget(e,t,o){const n=o();if(n){return{type:"destination",destination:this.readPdfDestination(e,n)}}{const o=t();if(o){return{type:"action",action:this.readPdfAction(e,o)}}}}createLocalDestPtr(e,o){var n,i;const r=this.pdfiumModule.FPDF_LoadPage(e,o.pageIndex);if(!r)return 0;try{if(o.zoom.mode===t.PdfZoomMode.XYZ){const{x:e,y:t,zoom:n}=o.zoom.params;return this.pdfiumModule.EPDFDest_CreateXYZ(r,!0,e,!0,t,!0,n)}let e,a=[];switch(o.zoom.mode){case t.PdfZoomMode.FitPage:e=t.PdfZoomMode.FitPage;break;case t.PdfZoomMode.FitHorizontal:e=t.PdfZoomMode.FitHorizontal,a=[(null==(n=o.view)?void 0:n[0])??0];break;case t.PdfZoomMode.FitVertical:e=t.PdfZoomMode.FitVertical,a=[(null==(i=o.view)?void 0:i[0])??0];break;case t.PdfZoomMode.FitRectangle:{const n=o.view??[];a=[n[0]??0,n[1]??0,n[2]??0,n[3]??0],e=t.PdfZoomMode.FitRectangle}break;case t.PdfZoomMode.Unknown:default:return 0}return this.withFloatArray(a,(t,o)=>this.pdfiumModule.EPDFDest_CreateView(r,e,t,o))}finally{this.pdfiumModule.FPDF_ClosePage(r)}}applyBookmarkTarget(e,o,n){if("destination"===n.type){const t=this.createLocalDestPtr(e,n.destination);if(!t)return!1;return!!this.pdfiumModule.EPDFBookmark_SetDest(e,o,t)}const i=n.action;switch(i.type){case t.PdfActionType.Goto:{const t=this.createLocalDestPtr(e,i.destination);if(!t)return!1;const n=this.pdfiumModule.EPDFAction_CreateGoTo(e,t);return!!n&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,o,n)}case t.PdfActionType.URI:{const t=this.pdfiumModule.EPDFAction_CreateURI(e,i.uri);return!!t&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,o,t)}case t.PdfActionType.LaunchAppOrOpenFile:{const t=this.withWString(i.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!t&&!!this.pdfiumModule.EPDFBookmark_SetAction(e,o,t)}case t.PdfActionType.RemoteGoto:case t.PdfActionType.Unsupported:default:return!1}}applyLinkTarget(e,o,n){if("destination"===n.type){const t=this.createLocalDestPtr(e,n.destination);if(!t)return!1;const i=this.pdfiumModule.EPDFAction_CreateGoTo(e,t);return!!i&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,i)}const i=n.action;switch(i.type){case t.PdfActionType.Goto:{const t=this.createLocalDestPtr(e,i.destination);if(!t)return!1;const n=this.pdfiumModule.EPDFAction_CreateGoTo(e,t);return!!n&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,n)}case t.PdfActionType.URI:{const t=this.pdfiumModule.EPDFAction_CreateURI(e,i.uri);return!!t&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,t)}case t.PdfActionType.LaunchAppOrOpenFile:{const t=this.withWString(i.path,t=>this.pdfiumModule.EPDFAction_CreateLaunch(e,t));return!!t&&!!this.pdfiumModule.EPDFAnnot_SetAction(o,t)}case t.PdfActionType.RemoteGoto:case t.PdfActionType.Unsupported:default:return!1}}readPdfAction(e,o){let n;switch(this.pdfiumModule.FPDFAction_GetType(o)){case t.PdfActionType.Unsupported:n={type:t.PdfActionType.Unsupported};break;case t.PdfActionType.Goto:{const i=this.pdfiumModule.FPDFAction_GetDest(e,o);if(i){const o=this.readPdfDestination(e,i);n={type:t.PdfActionType.Goto,destination:o}}else n={type:t.PdfActionType.Unsupported}}break;case t.PdfActionType.RemoteGoto:n={type:t.PdfActionType.Unsupported};break;case t.PdfActionType.URI:{const r=i(this.pdfiumModule.pdfium,(t,n)=>this.pdfiumModule.FPDFAction_GetURIPath(e,o,t,n),this.pdfiumModule.pdfium.UTF8ToString);n={type:t.PdfActionType.URI,uri:r}}break;case t.PdfActionType.LaunchAppOrOpenFile:{const e=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAction_GetFilePath(o,e,t),this.pdfiumModule.pdfium.UTF8ToString);n={type:t.PdfActionType.LaunchAppOrOpenFile,path:e}}}return n}readPdfDestination(e,o){const n=this.pdfiumModule.FPDFDest_GetDestPageIndex(e,o),i=this.memoryManager.malloc(4),r=this.memoryManager.malloc(16),a=this.pdfiumModule.FPDFDest_GetView(o,i,r),s=this.pdfiumModule.pdfium.getValue(i,"i32"),d=[];for(let t=0;t<s;t++){const e=r+4*t;d.push(this.pdfiumModule.pdfium.getValue(e,"float"))}if(this.memoryManager.free(i),this.memoryManager.free(r),a===t.PdfZoomMode.XYZ){const e=this.memoryManager.malloc(1),t=this.memoryManager.malloc(1),i=this.memoryManager.malloc(1),r=this.memoryManager.malloc(4),s=this.memoryManager.malloc(4),l=this.memoryManager.malloc(4);if(this.pdfiumModule.FPDFDest_GetLocationInPage(o,e,t,i,r,s,l)){const o=this.pdfiumModule.pdfium.getValue(e,"i8"),u=this.pdfiumModule.pdfium.getValue(t,"i8"),h=this.pdfiumModule.pdfium.getValue(i,"i8"),c=o?this.pdfiumModule.pdfium.getValue(r,"float"):0,g=u?this.pdfiumModule.pdfium.getValue(s,"float"):0,f=h?this.pdfiumModule.pdfium.getValue(l,"float"):0;return this.memoryManager.free(e),this.memoryManager.free(t),this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(s),this.memoryManager.free(l),{pageIndex:n,zoom:{mode:a,params:{x:c,y:g,zoom:f}},view:d}}return this.memoryManager.free(e),this.memoryManager.free(t),this.memoryManager.free(i),this.memoryManager.free(r),this.memoryManager.free(s),this.memoryManager.free(l),{pageIndex:n,zoom:{mode:a,params:{x:0,y:0,zoom:0}},view:d}}return{pageIndex:n,zoom:{mode:a},view:d}}readPdfAttachment(e,t){const o=this.pdfiumModule.FPDFDoc_GetAttachment(e,t),n=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetName(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),r=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.EPDFAttachment_GetDescription(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),a=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetSubtype(o,e,t),this.pdfiumModule.pdfium.UTF16ToString),s=this.getAttachmentDate(o,"CreationDate"),d=i(this.pdfiumModule.pdfium,(e,t)=>this.pdfiumModule.FPDFAttachment_GetStringValue(o,"Checksum",e,t),this.pdfiumModule.pdfium.UTF16ToString);return{index:t,name:n,description:r,mimeType:a,size:this.getAttachmentNumber(o,"Size"),creationDate:s,checksum:d}}convertDevicePointToPagePoint(e,t){const o=e.size.width,n=e.size.height,i=3&e.rotation;return 0===i?{x:t.x,y:n-t.y}:1===i?{x:t.y,y:t.x}:2===i?{x:o-t.x,y:t.y}:{x:n-t.y,y:o-t.x}}convertPagePointToDevicePoint(e,t){const o=e.size.width,n=e.size.height,i=3&e.rotation;return 0===i?{x:t.x,y:n-t.y}:1===i?{x:t.y,y:t.x}:2===i?{x:o-t.x,y:t.y}:{x:o-t.y,y:n-t.x}}convertPageRectToDeviceRect(e,t){const{x:o,y:n}=this.convertPagePointToDevicePoint(e,{x:t.left,y:t.top});return{origin:{x:o,y:n},size:{width:Math.abs(t.right-t.left),height:Math.abs(t.top-t.bottom)}}}readPageAnnoAppearanceStreams(e){return{normal:this.readPageAnnoAppearanceStream(e,t.AppearanceMode.Normal),rollover:this.readPageAnnoAppearanceStream(e,t.AppearanceMode.Rollover),down:this.readPageAnnoAppearanceStream(e,t.AppearanceMode.Down)}}readPageAnnoAppearanceStream(e,o=t.AppearanceMode.Normal){const n=2*(this.pdfiumModule.FPDFAnnot_GetAP(e,o,0,0)+1),i=this.memoryManager.malloc(n);this.pdfiumModule.FPDFAnnot_GetAP(e,o,i,n);const r=this.pdfiumModule.pdfium.UTF16ToString(i);return this.memoryManager.free(i),r}setPageAnnoAppearanceStream(e,o=t.AppearanceMode.Normal,n){const i=2*(n.length+1),r=this.memoryManager.malloc(i);try{this.pdfiumModule.pdfium.stringToUTF16(n,r,i);return!!this.pdfiumModule.FPDFAnnot_SetAP(e,o,r)}finally{this.memoryManager.free(r)}}setPageAnnoRect(e,t,o){const n=Math.floor(o.origin.x),i=Math.floor(o.origin.y),r=Math.floor(o.origin.x+o.size.width),a=Math.floor(o.origin.y+o.size.height),s=this.convertDevicePointToPagePoint(e,{x:n,y:i}),d=this.convertDevicePointToPagePoint(e,{x:r,y:i}),l=this.convertDevicePointToPagePoint(e,{x:r,y:a}),u=this.convertDevicePointToPagePoint(e,{x:n,y:a});let h=Math.min(s.x,d.x,l.x,u.x),c=Math.max(s.x,d.x,l.x,u.x),g=Math.min(s.y,d.y,l.y,u.y),f=Math.max(s.y,d.y,l.y,u.y);h>c&&([h,c]=[c,h]),g>f&&([g,f]=[f,g]);const m=this.memoryManager.malloc(16),p=this.pdfiumModule.pdfium;p.setValue(m+0,h,"float"),p.setValue(m+4,f,"float"),p.setValue(m+8,c,"float"),p.setValue(m+12,g,"float");const P=this.pdfiumModule.FPDFAnnot_SetRect(t,m);return this.memoryManager.free(m),!!P}readPageAnnoRect(e){const t=this.memoryManager.malloc(16),o={left:0,top:0,right:0,bottom:0};return this.pdfiumModule.FPDFAnnot_GetRect(e,t)&&(o.left=this.pdfiumModule.pdfium.getValue(t,"float"),o.top=this.pdfiumModule.pdfium.getValue(t+4,"float"),o.right=this.pdfiumModule.pdfium.getValue(t+8,"float"),o.bottom=this.pdfiumModule.pdfium.getValue(t+12,"float")),this.memoryManager.free(t),o}getHighlightRects(e,t,o,n){const i=this.pdfiumModule.FPDFText_CountRects(t,o,n),r=[],a=this.memoryManager.malloc(8),s=this.memoryManager.malloc(8),d=this.memoryManager.malloc(8),l=this.memoryManager.malloc(8);for(let u=0;u<i;u++){if(!this.pdfiumModule.FPDFText_GetRect(t,u,a,s,d,l))continue;const o=this.pdfiumModule.pdfium.getValue(a,"double"),n=this.pdfiumModule.pdfium.getValue(s,"double"),i=this.pdfiumModule.pdfium.getValue(d,"double"),h=this.pdfiumModule.pdfium.getValue(l,"double"),c=this.convertPagePointToDevicePoint(e,{x:o,y:n}),g=this.convertPagePointToDevicePoint(e,{x:i,y:n}),f=this.convertPagePointToDevicePoint(e,{x:i,y:h}),m=this.convertPagePointToDevicePoint(e,{x:o,y:h}),p=[c.x,g.x,f.x,m.x],P=[c.y,g.y,f.y,m.y],F=Math.min(...p),M=Math.min(...P),y=Math.max(...p)-F,A=Math.max(...P)-M;r.push({origin:{x:F,y:M},size:{width:Math.ceil(y),height:Math.ceil(A)}})}return this.memoryManager.free(a),this.memoryManager.free(s),this.memoryManager.free(d),this.memoryManager.free(l),r}searchInPage(e,o,n,i){this.logger.debug(T,C,"searchInPage",e,o,n,i),this.logger.perf(T,C,"SearchInPage","Begin",`${e.id}-${o.index}`);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const a=2*(n.length+1),s=this.memoryManager.malloc(a);this.pdfiumModule.pdfium.stringToUTF16(n,s,a);try{const e=this.searchAllInPage(r,o,s,i);return t.PdfTaskHelper.resolve(e)}finally{this.memoryManager.free(s)}}getAnnotationsBatch(e,o){this.logger.debug(T,C,"getAnnotationsBatch",e.id,o.length);const n=new t.Task;return queueMicrotask(()=>{this.logger.perf(T,C,"GetAnnotationsBatch","Begin",e.id);const i=this.cache.getContext(e.id);if(!i)return void n.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const r={},a=o.length;for(let e=0;e<o.length;e++){const t=o[e],s=this.readPageAnnotationsRaw(i,t);r[t.index]=s,n.progress({pageIndex:t.index,result:s,completed:e+1,total:a})}this.logger.perf(T,C,"GetAnnotationsBatch","End",e.id),n.resolve(r)}),n}searchBatch(e,o,n,i){this.logger.debug(T,C,"searchBatch",e.id,o.length,n);const r=new t.Task;return queueMicrotask(()=>{this.logger.perf(T,C,"SearchBatch","Begin",e.id);const a=this.cache.getContext(e.id);if(!a)return void r.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const s=2*(n.length+1),d=this.memoryManager.malloc(s);this.pdfiumModule.pdfium.stringToUTF16(n,d,s);try{const t={},n=o.length;for(let e=0;e<o.length;e++){const s=o[e],l=this.searchAllInPage(a,s,d,i);t[s.index]=l,r.progress({pageIndex:s.index,result:l,completed:e+1,total:n})}this.logger.perf(T,C,"SearchBatch","End",e.id),r.resolve(t)}finally{this.memoryManager.free(d)}}),r}buildContext(e,t,o,n=30){const i=/[\s\u00A0.,;:!?()\[\]{}<>/\\\-"'`"”\u2013\u2014]/;let r=t;for(;r>0&&i.test(e[r-1]);)r--;let a=0;for(;r>0&&a<n;)r--,i.test(e[r])||a++;r=(t=>{for(;t>0&&!i.test(e[t-1]);)t--;return t})(r);let s=t+o;for(;s<e.length&&i.test(e[s]);)s++;for(a=0;s<e.length&&a<n;)i.test(e[s])||a++,s++;s=(t=>{for(;t<e.length&&!i.test(e[t]);)t++;return t})(s);const d=e.slice(r,t).replace(/\s+/g," ").trimStart(),l=e.slice(t,t+o),u=e.slice(t+o,s).replace(/\s+/g," ").trimEnd();return{before:this.tidy(d),match:this.tidy(l),after:this.tidy(u),truncatedLeft:r>0,truncatedRight:s<e.length}}tidy(e){return e.replace(/-\uFFFE\s*/g,"").replace(/[\uFFFE\u00AD\u200B\u2060\uFEFF]/g,"").replace(/\s+/g," ")}searchAllInPage(e,t,o,n){return e.borrowPage(t.index,e=>{const i=e.getTextPage(),r=this.pdfiumModule.FPDFText_CountChars(i),a=this.memoryManager.malloc(2*(r+1));this.pdfiumModule.FPDFText_GetText(i,0,r,a);const s=this.pdfiumModule.pdfium.UTF16ToString(a);this.memoryManager.free(a);const d=[],l=this.pdfiumModule.FPDFText_FindStart(i,o,n,0);for(;this.pdfiumModule.FPDFText_FindNext(l);){const e=this.pdfiumModule.FPDFText_GetSchResultIndex(l),o=this.pdfiumModule.FPDFText_GetSchCount(l),n=this.getHighlightRects(t,i,e,o),r=this.buildContext(s,e,o);d.push({pageIndex:t.index,charIndex:e,charCount:o,rects:n,context:r})}return this.pdfiumModule.FPDFText_FindClose(l),d})}preparePrintDocument(e,o){const{includeAnnotations:n=!0,pageRange:i=null}=o??{};this.logger.debug(T,C,"preparePrintDocument",e,o),this.logger.perf(T,C,"PreparePrintDocument","Begin",e.id);const r=this.cache.getContext(e.id);if(!r)return this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document is not open"});const a=this.pdfiumModule.FPDF_CreateNewDocument();if(!a)return this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantCreateNewDoc,message:"Cannot create print document"});try{const o=this.sanitizePageRange(i,e.pageCount);if(!this.pdfiumModule.FPDF_ImportPages(a,r.docPtr,o??"",0))return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(T,C,"Failed to import pages for printing"),this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.CantImportPages,message:"Failed to import pages for printing"});if(!n){const o=this.removeAnnotationsFromPrintDocument(a);if(!o.success)return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(T,C,`Failed to remove annotations: ${o.error}`),this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:`Failed to prepare print document: ${o.error}`});this.logger.debug(T,C,`Removed ${o.annotationsRemoved} annotations from ${o.pagesProcessed} pages`)}const s=this.saveDocument(a);return this.pdfiumModule.FPDF_CloseDocument(a),this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.resolve(s)}catch(s){return a&&this.pdfiumModule.FPDF_CloseDocument(a),this.logger.error(T,C,"preparePrintDocument failed",s),this.logger.perf(T,C,"PreparePrintDocument","End",e.id),t.PdfTaskHelper.reject({code:t.PdfErrorCode.Unknown,message:s instanceof Error?s.message:"Failed to prepare print document"})}}removeAnnotationsFromPrintDocument(e){let t=0,o=0;try{const n=this.pdfiumModule.FPDF_GetPageCount(e);for(let i=0;i<n;i++){const n=this.pdfiumModule.EPDFPage_GetAnnotCountRaw(e,i);if(n<=0){o++;continue}let r=0;for(let o=n-1;o>=0;o--){this.pdfiumModule.EPDFPage_RemoveAnnotRaw(e,i,o)?(r++,t++):this.logger.warn(T,C,`Failed to remove annotation ${o} from page ${i}`)}if(r>0){const t=this.pdfiumModule.FPDF_LoadPage(e,i);t&&(this.pdfiumModule.FPDFPage_GenerateContent(t),this.pdfiumModule.FPDF_ClosePage(t))}o++}return{success:!0,annotationsRemoved:t,pagesProcessed:o}}catch(n){return{success:!1,annotationsRemoved:t,pagesProcessed:o,error:n instanceof Error?n.message:"Unknown error during annotation removal"}}}sanitizePageRange(e,t){if(!e||""===e.trim())return null;try{const o=[],n=e.split(",");for(const e of n){const n=e.trim();if(n.includes("-")){const[e,i]=n.split("-").map(e=>e.trim()),r=parseInt(e,10),a=parseInt(i,10);if(isNaN(r)||isNaN(a)){this.logger.warn(T,C,`Invalid range: ${n}`);continue}const s=Math.max(1,Math.min(r,t)),d=Math.max(1,Math.min(a,t));for(let t=s;t<=d;t++)o.includes(t)||o.push(t)}else{const e=parseInt(n,10);if(isNaN(e)){this.logger.warn(T,C,`Invalid page number: ${n}`);continue}const i=Math.max(1,Math.min(e,t));o.includes(i)||o.push(i)}}if(0===o.length)return this.logger.warn(T,C,"No valid pages in range, using all pages"),null;o.sort((e,t)=>e-t);const i=[];let r=o[0],a=o[0];for(let e=1;e<o.length;e++)o[e]===a+1||(r===a?i.push(r.toString()):a-r===1?(i.push(r.toString()),i.push(a.toString())):i.push(`${r}-${a}`),r=o[e]),a=o[e];r===a?i.push(r.toString()):a-r===1?(i.push(r.toString()),i.push(a.toString())):i.push(`${r}-${a}`);const s=i.join(",");return this.logger.debug(T,C,`Sanitized page range: "${e}" -> "${s}"`),s}catch(o){return this.logger.error(T,C,`Error sanitizing page range: ${o}`),null}}}exports.BitmapFormat=A,exports.FontFallbackManager=y,exports.PdfiumErrorCode=E,exports.PdfiumNative=x,exports.RenderFlag=D,exports.computeFormDrawParams=d,exports.createNodeFontLoader=function(e,t,o){return n=>{try{const i=t.join(o,n),r=e.readFileSync(i);return r instanceof Uint8Array?r:new Uint8Array(r)}catch{return null}}},exports.createPdfiumEngine=async function(t,i){const r=await fetch(t),a=await r.arrayBuffer(),s=await e.init({wasmBinary:a}),d=new x(s,{logger:null==i?void 0:i.logger,fontFallback:null==i?void 0:i.fontFallback});return new o.PdfEngine(d,{imageConverter:n.browserImageDataToBlobConverter,logger:null==i?void 0:i.logger})},exports.isValidCustomKey=s,exports.readArrayBuffer=r,exports.readString=i;
2
- //# sourceMappingURL=direct-engine-Dwkk7o9U.cjs.map